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.
- 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/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 +61 -9
- package/dist/cjs/script/index.d.ts.map +1 -1
- package/dist/cjs/script/index.js +173 -48
- 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/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 +61 -9
- package/dist/esm/script/index.d.ts.map +1 -1
- package/dist/esm/script/index.js +229 -56
- package/dist/esm/script/index.js.map +1 -1
- package/package.json +1 -1
- package/skills/oakscript/reference/pine-differences.md +3 -3
- package/skills/oakscript/reference/timeframes-symbols.md +10 -0
- package/src/index.ts +1 -1
- package/src/script/incremental.ts +35 -1
- package/src/script/index.ts +295 -61
|
@@ -71,9 +71,9 @@ The Pine constants exist with their Pine names: `shape.*`, `location.*`, `size.*
|
|
|
71
71
|
first or last bar are not drawn).
|
|
72
72
|
- `fill()` accepts `show_last` / `fillgaps` / `display` and ignores them.
|
|
73
73
|
- `input.enum` does not exist (no `enum` declarations): use `input.string(..., { options })`.
|
|
74
|
-
- `request.*`: only `request.security
|
|
75
|
-
|
|
76
|
-
`request.currency_rate`, `request.footprint`. `ticker.*`: only `ticker.heikinashi` and `ticker.standard`.
|
|
74
|
+
- `request.*`: only `request.security`, `request.security_lower_tf` and `request.seed` (the host maps the seed
|
|
75
|
+
series to a symbol). No `request.financial`, `request.dividends`, `request.earnings`, `request.splits`,
|
|
76
|
+
`request.economic`, `request.currency_rate`, `request.footprint`. `ticker.*`: only `ticker.heikinashi` and `ticker.standard`.
|
|
77
77
|
- `math.random(min, max, seed)`: with a seed, Pine's sequence, but one generator per seed value (Pine has one
|
|
78
78
|
per call site): two calls with the same seed need `callsite.random(seed)`.
|
|
79
79
|
- `math.log`, `math.exp`, `math.pow`, `math.sin`, `math.cos`, `math.tan`, `math.log10` can differ from Pine in
|
|
@@ -77,6 +77,16 @@ const upVolume = eachBar((c) => vols[c.i].reduce((sum, v) => sum + v, 0));
|
|
|
77
77
|
plot(upVolume, "Up volume", { style: plot.style_columns, color: color.teal });
|
|
78
78
|
```
|
|
79
79
|
|
|
80
|
+
### Seed data
|
|
81
|
+
|
|
82
|
+
`request.seed(source, symbol, expression)` reads a seed data series on the chart timeframe: it is
|
|
83
|
+
`request.security` of the symbol the host gives that series (by default `"<SOURCE>:<SYMBOL>"` upper-cased).
|
|
84
|
+
|
|
85
|
+
```js
|
|
86
|
+
indicator("Seed value", { overlay: false });
|
|
87
|
+
plot(request.seed("seed_crypto_santiment", "BTC_DEV_ACTIVITY", () => close), "Dev activity");
|
|
88
|
+
```
|
|
89
|
+
|
|
80
90
|
## Timeframe values
|
|
81
91
|
|
|
82
92
|
- `timeframe.period` (`"60"`, `"1D"`...), `timeframe.multiplier`, `timeframe.isintraday`, `timeframe.isdaily`,
|
package/src/index.ts
CHANGED
|
@@ -232,7 +232,7 @@ export type { LightweightSeriesDefinitions } from './runtime/adapters/Lightweigh
|
|
|
232
232
|
export { SimpleInputAdapter } from './runtime/adapters/SimpleInputAdapter.js';
|
|
233
233
|
|
|
234
234
|
// Version
|
|
235
|
-
export const VERSION = '0.
|
|
235
|
+
export const VERSION = '0.17.1';
|
|
236
236
|
|
|
237
237
|
/**
|
|
238
238
|
* Library information
|
|
@@ -139,8 +139,9 @@ const hooks: SeriesRunHooks = {
|
|
|
139
139
|
return values && values.length >= run.from ? { values, from: run.from } : null;
|
|
140
140
|
},
|
|
141
141
|
computed(series, values) {
|
|
142
|
+
// also a Series of the body first read in an eachBar() callback (its values do not depend on the bar running, #206)
|
|
142
143
|
const run = active;
|
|
143
|
-
if (!run
|
|
144
|
+
if (!run) return;
|
|
144
145
|
const slot = slotOf(series);
|
|
145
146
|
if (slot !== undefined) run.next.series[slot] = values;
|
|
146
147
|
else run.next.kept.set(series, values);
|
|
@@ -234,6 +235,39 @@ export function copyValue(value: unknown): unknown {
|
|
|
234
235
|
return out;
|
|
235
236
|
}
|
|
236
237
|
|
|
238
|
+
/** {@link plainCopy} of a value that is not plain data. */
|
|
239
|
+
export const NOT_COPIED: unique symbol = Symbol('not copied');
|
|
240
|
+
|
|
241
|
+
/** A deep copy of plain data (numbers, strings, booleans, arrays, plain objects, Map, Set), else {@link NOT_COPIED}. */
|
|
242
|
+
export function plainCopy(value: unknown): unknown {
|
|
243
|
+
if (typeof value === 'function') return NOT_COPIED;
|
|
244
|
+
if (value === null || typeof value !== 'object') return value;
|
|
245
|
+
const all = (items: unknown[]): unknown[] | typeof NOT_COPIED => {
|
|
246
|
+
const out = items.map(plainCopy);
|
|
247
|
+
return out.includes(NOT_COPIED) ? NOT_COPIED : out;
|
|
248
|
+
};
|
|
249
|
+
if (Array.isArray(value)) return all(value);
|
|
250
|
+
if (value instanceof Map) {
|
|
251
|
+
const entries = all([...value].flat());
|
|
252
|
+
if (entries === NOT_COPIED) return NOT_COPIED;
|
|
253
|
+
const m = new Map();
|
|
254
|
+
for (let k = 0; k < entries.length; k += 2) m.set(entries[k], entries[k + 1]);
|
|
255
|
+
return m;
|
|
256
|
+
}
|
|
257
|
+
if (value instanceof Set) {
|
|
258
|
+
const items = all([...value]);
|
|
259
|
+
return items === NOT_COPIED ? NOT_COPIED : new Set(items);
|
|
260
|
+
}
|
|
261
|
+
const proto = Object.getPrototypeOf(value);
|
|
262
|
+
if (proto !== Object.prototype && proto !== null) return NOT_COPIED;
|
|
263
|
+
const keys = Object.keys(value);
|
|
264
|
+
const values = all(keys.map((k) => (value as Record<string, unknown>)[k]));
|
|
265
|
+
if (values === NOT_COPIED) return NOT_COPIED;
|
|
266
|
+
const out: Record<string, unknown> = {};
|
|
267
|
+
keys.forEach((k, j) => (out[k] = values[j]));
|
|
268
|
+
return out;
|
|
269
|
+
}
|
|
270
|
+
|
|
237
271
|
/**
|
|
238
272
|
* A feature an incremental run does not resume: a recorded run keeps its result (it is a full run) and marks the next
|
|
239
273
|
* updates as full runs; a resumed run stops.
|
package/src/script/index.ts
CHANGED
|
@@ -396,6 +396,13 @@ export class StrategyRecorder {
|
|
|
396
396
|
readonly varipStarts: unknown[][] = [];
|
|
397
397
|
/** Current `varip` values: kept through the intrabar runs (no rollback). */
|
|
398
398
|
readonly varip: unknown[] = [];
|
|
399
|
+
/**
|
|
400
|
+
* Why the intrabar runs of this recorder calculate all the bars before their bar (a feature that is not resumed,
|
|
401
|
+
* or a verification difference); null while they are resumed (see {@link executeIntrabar}).
|
|
402
|
+
*/
|
|
403
|
+
get intrabarFullRunReason(): string | null {
|
|
404
|
+
return intrabarChains.get(this)?.reason ?? null;
|
|
405
|
+
}
|
|
399
406
|
}
|
|
400
407
|
|
|
401
408
|
/** Module state of a run, saved around a nested run (an intrabar run inside the bar loop of the main run). */
|
|
@@ -474,6 +481,8 @@ function runBody(
|
|
|
474
481
|
): ScriptRunResult {
|
|
475
482
|
// A run inside another one (an intrabar run of a strategy) puts the outer run back when it ends.
|
|
476
483
|
const outer = ctx ? saveRunState() : null;
|
|
484
|
+
// A main run with a recorder starts a new backtest: its intrabar runs start again (#206).
|
|
485
|
+
if (options.recorder) intrabarChains.delete(options.recorder);
|
|
477
486
|
// A plain run inside an incremental one is not part of it.
|
|
478
487
|
const outerInc = inc ? incremental.beginRun(inc) : incremental.suspendRun();
|
|
479
488
|
ctxBars.setAll(barsInput);
|
|
@@ -549,18 +558,101 @@ export interface IntrabarOptions {
|
|
|
549
558
|
engine: StrategyEngine;
|
|
550
559
|
/** The recorder of the main run. */
|
|
551
560
|
recorder: StrategyRecorder;
|
|
561
|
+
/**
|
|
562
|
+
* Resume the run from the state at the start of the bar (default true, #206); false calculates all the bars before
|
|
563
|
+
* it, as before.
|
|
564
|
+
*/
|
|
565
|
+
resume?: boolean;
|
|
566
|
+
/**
|
|
567
|
+
* Resumed runs also calculated in full and compared, the first ones of a backtest (default 2): a difference makes the
|
|
568
|
+
* next intrabar runs full ones (a script that keeps state outside persist() boxes).
|
|
569
|
+
*/
|
|
570
|
+
verify?: number;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/** What {@link executeIntrabar} calculated. */
|
|
574
|
+
export interface IntrabarUpdate {
|
|
575
|
+
/** First bar calculated: 0 for a full run, else the bar of the previous intrabar run (#206) */
|
|
576
|
+
from: number;
|
|
577
|
+
/** The run was resumed from the state of the bar before `from` */
|
|
578
|
+
incremental: boolean;
|
|
579
|
+
/** Why the intrabar runs of the backtest are full runs (null: resumed) */
|
|
580
|
+
fullRunReason: string | null;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/** The intrabar runs of a backtest (one recorder): each one resumes from the state the previous one kept (#206). */
|
|
584
|
+
interface IntrabarChain {
|
|
585
|
+
body: () => void;
|
|
586
|
+
inputs: Record<string, unknown>;
|
|
587
|
+
chart: ChartContext;
|
|
588
|
+
engine: StrategyEngine;
|
|
589
|
+
lastBarIndex: number;
|
|
590
|
+
/** State kept by the last run (null: the next run is a full one that records it) */
|
|
591
|
+
memory: incremental.RunMemory | null;
|
|
592
|
+
/** Bars of the last run */
|
|
593
|
+
n: number;
|
|
594
|
+
reason: string | null;
|
|
595
|
+
verifyLeft: number;
|
|
596
|
+
}
|
|
597
|
+
const intrabarChains = new WeakMap<StrategyRecorder, IntrabarChain>();
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* The live engine of an intrabar run with its calls logged (`log`, to compare two runs) and its order calls, when
|
|
601
|
+
* `writes` is given, kept there instead of made (a resumed run gives them to the engine once it has ended: a run
|
|
602
|
+
* stopped in the middle makes none).
|
|
603
|
+
*/
|
|
604
|
+
function intrabarEngine(engine: StrategyEngine, log: unknown[] | null, writes: Array<() => void> | null): StrategyEngine {
|
|
605
|
+
const read = <T>(name: string, args: unknown[], value: T): T => {
|
|
606
|
+
log?.push([name, ...args, value]);
|
|
607
|
+
return value;
|
|
608
|
+
};
|
|
609
|
+
const write = (name: string, args: unknown[], call: () => void): void => {
|
|
610
|
+
log?.push([name, ...args]);
|
|
611
|
+
if (writes) writes.push(call);
|
|
612
|
+
else call();
|
|
613
|
+
};
|
|
614
|
+
return {
|
|
615
|
+
...forward(engine),
|
|
616
|
+
entry: (id, direction, options) => write('entry', [id, direction, options], () => engine.entry(id, direction, options)),
|
|
617
|
+
order: (id, direction, options) => write('order', [id, direction, options], () => engine.order(id, direction, options)),
|
|
618
|
+
exit: (id, options) => write('exit', [id, options], () => engine.exit(id, options)),
|
|
619
|
+
close: (id, options) => write('close', [id, options], () => engine.close(id, options)),
|
|
620
|
+
close_all: (options) => write('close_all', [options], () => engine.close_all(options)),
|
|
621
|
+
cancel: (id) => write('cancel', [id], () => engine.cancel(id)),
|
|
622
|
+
cancel_all: () => write('cancel_all', [], () => engine.cancel_all()),
|
|
623
|
+
get: (name) => read('get', [name], engine.get(name)),
|
|
624
|
+
openTrade: (index) => read('openTrade', [index], engine.openTrade(index)),
|
|
625
|
+
closedTrade: (index) => read('closedTrade', [index], engine.closedTrade(index)),
|
|
626
|
+
defaultEntryQty: engine.defaultEntryQty
|
|
627
|
+
? (price) => read('defaultEntryQty', [price], engine.defaultEntryQty!(price))
|
|
628
|
+
: undefined,
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/** Puts the `varip` values back to a copy taken before a run. */
|
|
633
|
+
function setVarip(recorder: StrategyRecorder, values: unknown[]): void {
|
|
634
|
+
recorder.varip.length = 0;
|
|
635
|
+
recorder.varip.push(...values);
|
|
552
636
|
}
|
|
553
637
|
|
|
554
638
|
/**
|
|
555
639
|
* Runs a strategy once more on a bar, inside the bar (PineScript `calc_on_order_fills` and calculations on the
|
|
556
640
|
* ticks of history bars): `bars` holds the bars up to that bar, the last one as it stands at the tick (its close is
|
|
557
|
-
* the tick price, its high and low the extremes reached so far). The script's
|
|
558
|
-
*
|
|
559
|
-
*
|
|
560
|
-
*
|
|
561
|
-
*
|
|
562
|
-
*
|
|
563
|
-
*
|
|
641
|
+
* the tick price, its high and low the extremes reached so far). The script's variables come back to their state at
|
|
642
|
+
* the start of the bar (PineScript rollback), except `varip` ones. In strategy.eachBar(), the bars before replay the
|
|
643
|
+
* engine's answers that the main run recorded (their order calls are dropped), and the bar itself calls
|
|
644
|
+
* `options.engine` without processBar / processClose (the host is filling its orders). That bar is a confirmed
|
|
645
|
+
* history bar (`barstate.isconfirmed`); `barstate.islast`, `last_bar_index` and `BarContext.n` keep the chart's last
|
|
646
|
+
* bar. Strategy risk rules are not declared again, and the outputs (plots, drawings) are dropped. Re-entrant: the host
|
|
647
|
+
* calls it inside the bar loop of the main run.
|
|
648
|
+
*
|
|
649
|
+
* Resumed runs (#206): the intrabar runs of a backtest (same recorder, script, inputs, chart and engine) keep the state
|
|
650
|
+
* of the script as createScriptRun does, so a run calculates its bar only (and the bars since the previous intrabar
|
|
651
|
+
* run), not all the bars before it; the order calls and `strategy.*` reads are the same as in a full run. The bars
|
|
652
|
+
* before `options.bar` must be the main run's (the same on every call). A script that keeps state outside `persist()`
|
|
653
|
+
* boxes (a `let` variable outside the callbacks that a callback changes), or uses a feature that is not resumed, gets
|
|
654
|
+
* full runs (`fullRunReason`); the first resumed runs are also calculated in full and compared (`verify`). A resumed
|
|
655
|
+
* run gives its order calls to the engine once it has ended.
|
|
564
656
|
*/
|
|
565
657
|
export function executeIntrabar(
|
|
566
658
|
body: () => void,
|
|
@@ -568,25 +660,130 @@ export function executeIntrabar(
|
|
|
568
660
|
inputs: Record<string, unknown>,
|
|
569
661
|
chart: ChartContext,
|
|
570
662
|
options: IntrabarOptions
|
|
571
|
-
):
|
|
572
|
-
const
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
663
|
+
): IntrabarUpdate {
|
|
664
|
+
const recorder = options.recorder;
|
|
665
|
+
// History bars are confirmed, also on their ticks (the reference app: a barstate.isconfirmed entry fills on them).
|
|
666
|
+
const runChart: ChartContext = { ...chart, lastBarConfirmed: true, realtime: false };
|
|
667
|
+
const execute = (engine: StrategyEngine, inc: incremental.ActiveRun | null): void => {
|
|
668
|
+
const run: IntrabarRun = { bar: options.bar, lastBarIndex: options.lastBarIndex, engine, recorder };
|
|
669
|
+
runBody(
|
|
670
|
+
() => {
|
|
671
|
+
intrabarRun = run;
|
|
672
|
+
varipRun = { slot: 0, recorder, mode: 'live', scratch: null };
|
|
673
|
+
body();
|
|
674
|
+
},
|
|
675
|
+
bars,
|
|
676
|
+
inputs,
|
|
677
|
+
runChart,
|
|
678
|
+
{ strategyEngine: () => engine },
|
|
679
|
+
inc
|
|
680
|
+
);
|
|
681
|
+
};
|
|
682
|
+
const fullRun = (reason: string | null): IntrabarUpdate => {
|
|
683
|
+
execute(options.engine, null);
|
|
684
|
+
return { from: 0, incremental: false, fullRunReason: reason };
|
|
685
|
+
};
|
|
686
|
+
if (options.resume === false) return fullRun('resume: false');
|
|
687
|
+
const n = bars.length;
|
|
688
|
+
if (options.bar !== n - 1) return fullRun('the bar is not the last of the bars');
|
|
689
|
+
|
|
690
|
+
let chain = intrabarChains.get(recorder);
|
|
691
|
+
if (
|
|
692
|
+
!chain || chain.body !== body || chain.engine !== options.engine || chain.lastBarIndex !== options.lastBarIndex ||
|
|
693
|
+
!sameResult(chain.inputs, inputs) || !sameChart(chain.chart, runChart)
|
|
694
|
+
) {
|
|
695
|
+
chain = {
|
|
696
|
+
body,
|
|
697
|
+
inputs,
|
|
698
|
+
chart: runChart,
|
|
699
|
+
engine: options.engine,
|
|
700
|
+
lastBarIndex: options.lastBarIndex,
|
|
701
|
+
memory: null,
|
|
702
|
+
n: 0,
|
|
703
|
+
reason: null,
|
|
704
|
+
verifyLeft: options.verify ?? 2,
|
|
705
|
+
};
|
|
706
|
+
intrabarChains.set(recorder, chain);
|
|
707
|
+
}
|
|
708
|
+
if (chain.reason) return fullRun(chain.reason);
|
|
709
|
+
|
|
710
|
+
const memory = chain.memory;
|
|
711
|
+
// A resumed run changes the memory in place: it is usable again only when the run has ended.
|
|
712
|
+
chain.memory = null;
|
|
713
|
+
if (!memory || n < chain.n) {
|
|
714
|
+
const inc = newActiveRun('record', bars, 0, null);
|
|
715
|
+
execute(options.engine, inc);
|
|
716
|
+
if (inc.blocked) chain.reason = inc.blocked;
|
|
717
|
+
else {
|
|
718
|
+
chain.memory = inc.next;
|
|
719
|
+
chain.n = n;
|
|
720
|
+
}
|
|
721
|
+
return { from: 0, incremental: false, fullRunReason: chain.reason };
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
const from = chain.n - 1;
|
|
725
|
+
const start = incremental.plainCopy(recorder.varip);
|
|
726
|
+
if (start === incremental.NOT_COPIED) {
|
|
727
|
+
chain.reason = 'a varip value that is not plain data';
|
|
728
|
+
return fullRun(chain.reason);
|
|
729
|
+
}
|
|
730
|
+
const verifying = chain.verifyLeft > 0;
|
|
731
|
+
const log: unknown[] | null = verifying ? [] : null;
|
|
732
|
+
const writes: Array<() => void> = [];
|
|
733
|
+
const inc = newActiveRun('resume', bars, from, memory);
|
|
734
|
+
try {
|
|
735
|
+
execute(intrabarEngine(options.engine, log, writes), inc);
|
|
736
|
+
} catch (err) {
|
|
737
|
+
// The run is calculated in full instead: the varip values back to the start, the kept order calls dropped. An
|
|
738
|
+
// error of the script is the full run's (it throws it again).
|
|
739
|
+
setVarip(recorder, start as unknown[]);
|
|
740
|
+
if (err instanceof incremental.ResumeAborted) chain.reason = err.reason;
|
|
741
|
+
return fullRun(chain.reason);
|
|
742
|
+
}
|
|
743
|
+
if (verifying) {
|
|
744
|
+
chain.verifyLeft--;
|
|
745
|
+
const resumedVarip = incremental.plainCopy(recorder.varip);
|
|
746
|
+
setVarip(recorder, start as unknown[]);
|
|
747
|
+
const fullLog: unknown[] = [];
|
|
748
|
+
execute(intrabarEngine(options.engine, fullLog, null), null);
|
|
749
|
+
if (resumedVarip === incremental.NOT_COPIED || !sameResult(log, fullLog) || !sameResult(resumedVarip, recorder.varip)) {
|
|
750
|
+
chain.reason = 'a resumed intrabar run differs from a full run (state kept outside persist()?)';
|
|
751
|
+
return { from: 0, incremental: false, fullRunReason: chain.reason };
|
|
752
|
+
}
|
|
753
|
+
} else {
|
|
754
|
+
for (const call of writes) call();
|
|
755
|
+
}
|
|
756
|
+
chain.memory = inc.next;
|
|
757
|
+
chain.n = n;
|
|
758
|
+
return { from, incremental: true, fullRunReason: null };
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/** The state of an incremental run: a recorded one (full), or one resumed at bar `from` from `prev`. */
|
|
762
|
+
function newActiveRun(
|
|
763
|
+
mode: 'record' | 'resume',
|
|
764
|
+
b: Bar[],
|
|
765
|
+
from: number,
|
|
766
|
+
prev: incremental.RunMemory | null
|
|
767
|
+
): incremental.ActiveRun {
|
|
768
|
+
const next = incremental.emptyMemory(b.length);
|
|
769
|
+
// the block that draws stays the one of the previous run (the forming bar may not draw)
|
|
770
|
+
if (mode === 'resume' && prev) next.drawingBlock = prev.drawingBlock;
|
|
771
|
+
return {
|
|
772
|
+
mode,
|
|
773
|
+
from,
|
|
774
|
+
bars: b,
|
|
775
|
+
prev: mode === 'resume' ? prev : null,
|
|
776
|
+
next,
|
|
777
|
+
seriesSlot: 0,
|
|
778
|
+
taSlot: 0,
|
|
779
|
+
blockSlot: 0,
|
|
780
|
+
plotSlot: 0,
|
|
781
|
+
boxSlot: 0,
|
|
782
|
+
drawSlot: 0,
|
|
783
|
+
block: -1,
|
|
784
|
+
boxes: [],
|
|
785
|
+
blocked: null,
|
|
577
786
|
};
|
|
578
|
-
executeScript(
|
|
579
|
-
() => {
|
|
580
|
-
intrabarRun = run;
|
|
581
|
-
varipRun = { slot: 0, recorder: options.recorder, mode: 'live', scratch: null };
|
|
582
|
-
body();
|
|
583
|
-
},
|
|
584
|
-
bars,
|
|
585
|
-
inputs,
|
|
586
|
-
// History bars are confirmed, also on their ticks (the reference app: a barstate.isconfirmed entry fills on them).
|
|
587
|
-
{ ...chart, lastBarConfirmed: true, realtime: false },
|
|
588
|
-
{ strategyEngine: () => options.engine }
|
|
589
|
-
);
|
|
590
787
|
}
|
|
591
788
|
|
|
592
789
|
// ── Incremental runs (#196) ──────────────────────────────────────────────────
|
|
@@ -716,27 +913,8 @@ export function createScriptRun(
|
|
|
716
913
|
let reason: string | null = null;
|
|
717
914
|
let verifyLeft = options.verify ?? 2;
|
|
718
915
|
|
|
719
|
-
const newRun = (mode: 'record' | 'resume', b: Bar[], from: number): incremental.ActiveRun =>
|
|
720
|
-
|
|
721
|
-
// the block that draws stays the one of the previous run (the forming bar may not draw)
|
|
722
|
-
if (mode === 'resume' && memory) next.drawingBlock = memory.drawingBlock;
|
|
723
|
-
return {
|
|
724
|
-
mode,
|
|
725
|
-
from,
|
|
726
|
-
bars: b,
|
|
727
|
-
prev: mode === 'resume' ? memory : null,
|
|
728
|
-
next,
|
|
729
|
-
seriesSlot: 0,
|
|
730
|
-
taSlot: 0,
|
|
731
|
-
blockSlot: 0,
|
|
732
|
-
plotSlot: 0,
|
|
733
|
-
boxSlot: 0,
|
|
734
|
-
drawSlot: 0,
|
|
735
|
-
block: -1,
|
|
736
|
-
boxes: [],
|
|
737
|
-
blocked: null,
|
|
738
|
-
};
|
|
739
|
-
};
|
|
916
|
+
const newRun = (mode: 'record' | 'resume', b: Bar[], from: number): incremental.ActiveRun =>
|
|
917
|
+
newActiveRun(mode, b, from, memory);
|
|
740
918
|
|
|
741
919
|
const full = (b: Bar[], c: ChartContext): ScriptRunUpdate => {
|
|
742
920
|
memory = null;
|
|
@@ -823,7 +1001,8 @@ export interface VaripVariable<T> {
|
|
|
823
1001
|
*/
|
|
824
1002
|
export function varip<T>(initial: T): VaripVariable<T> {
|
|
825
1003
|
collector();
|
|
826
|
-
|
|
1004
|
+
// the intrabar runs of a backtest resume with varip values read in strategy.eachBar() (#206)
|
|
1005
|
+
if (!intrabarRun) incremental.nonIncremental('varip');
|
|
827
1006
|
const slot = varipRun.slot++;
|
|
828
1007
|
const state = varipRun;
|
|
829
1008
|
const rec = state.recorder;
|
|
@@ -839,7 +1018,11 @@ export function varip<T>(initial: T): VaripVariable<T> {
|
|
|
839
1018
|
};
|
|
840
1019
|
}
|
|
841
1020
|
if (rec.varip.length <= slot) rec.varip[slot] = initial;
|
|
842
|
-
const store = (): unknown[] =>
|
|
1021
|
+
const store = (): unknown[] => {
|
|
1022
|
+
// elsewhere, a resumed run would keep values of the bars before calculated with older varip values
|
|
1023
|
+
if (incremental.active && !ctx?.strategy?.inLoop) incremental.nonIncremental('varip used outside strategy.eachBar()');
|
|
1024
|
+
return state.mode === 'replay' && state.scratch ? state.scratch : rec.varip;
|
|
1025
|
+
};
|
|
843
1026
|
return {
|
|
844
1027
|
get value() {
|
|
845
1028
|
return store()[slot] as T;
|
|
@@ -1173,9 +1356,10 @@ export const bar_index = new Series(ctxBars, (_b, i) => i);
|
|
|
1173
1356
|
bar_index.fullHistory = true;
|
|
1174
1357
|
/** PineScript `last_bar_index`: the index of the last bar, on every bar. In a bar loop, `c.n - 1`. */
|
|
1175
1358
|
export const last_bar_index = new Series(ctxBars, (_b, _i, data) => {
|
|
1176
|
-
// the same value on every bar, changed by a new bar: not kept by an incremental run (#196)
|
|
1177
|
-
|
|
1178
|
-
|
|
1359
|
+
// the same value on every bar, changed by a new bar: not kept by an incremental run (#196), but the same in the
|
|
1360
|
+
// intrabar runs of a backtest (the chart's last bar, #206)
|
|
1361
|
+
if (!intrabarRun) incremental.nonIncremental('last_bar_index');
|
|
1362
|
+
return chartBarCount(data.length) - 1;
|
|
1179
1363
|
});
|
|
1180
1364
|
last_bar_index.fullHistory = true;
|
|
1181
1365
|
// built-in price variables keep the whole history (no 5000-bar limit)
|
|
@@ -2400,7 +2584,7 @@ function runBlock(
|
|
|
2400
2584
|
const b = bars();
|
|
2401
2585
|
// An intrabar run ends on its bar: the chart's last bar stays the main run's.
|
|
2402
2586
|
const lastIndex = intrabarRun ? intrabarRun.lastBarIndex : b.length - 1;
|
|
2403
|
-
let out: number[] =
|
|
2587
|
+
let out: number[] = [];
|
|
2404
2588
|
const cache = new Map<Series, number[]>();
|
|
2405
2589
|
// history buffers by source: the slot of a Series made by the script (matched across incremental runs), or the Series
|
|
2406
2590
|
const buffers = new Map<unknown, HistoryBuffer>();
|
|
@@ -2420,7 +2604,8 @@ function runBlock(
|
|
|
2420
2604
|
}
|
|
2421
2605
|
let start = 0;
|
|
2422
2606
|
let checkpoint: incremental.BlockCheckpoint | null = null;
|
|
2423
|
-
if (run?.mode
|
|
2607
|
+
if (run?.mode !== 'resume') out = new Array(b.length).fill(NaN);
|
|
2608
|
+
else {
|
|
2424
2609
|
const prev = run.prev?.blocks[slot];
|
|
2425
2610
|
if (!prev) incremental.nonIncremental('a new eachBar() block');
|
|
2426
2611
|
start = run.from;
|
|
@@ -2464,8 +2649,9 @@ function runBlock(
|
|
|
2464
2649
|
return idx;
|
|
2465
2650
|
},
|
|
2466
2651
|
get n() {
|
|
2467
|
-
// the bar count changes with each new bar: a value read from it is not kept by an incremental run
|
|
2468
|
-
|
|
2652
|
+
// the bar count changes with each new bar: a value read from it is not kept by an incremental run (the chart's
|
|
2653
|
+
// last bar of the intrabar runs of a backtest does not change)
|
|
2654
|
+
if (run && !intrabarRun) incremental.nonIncremental('BarContext.n');
|
|
2469
2655
|
return lastIndex + 1;
|
|
2470
2656
|
},
|
|
2471
2657
|
get time() {
|
|
@@ -2652,7 +2838,7 @@ function strategyEachBar(fn: (c: BarContext) => number | boolean | void): Series
|
|
|
2652
2838
|
const varipState = varipRun;
|
|
2653
2839
|
const replayLog: { answers: readonly unknown[]; next: number } = { answers: [], next: 0 };
|
|
2654
2840
|
const replayed = replayEngine(replayLog);
|
|
2655
|
-
return
|
|
2841
|
+
return runBlock((c) => {
|
|
2656
2842
|
const replay = c.i < intrabar.bar;
|
|
2657
2843
|
if (replay) {
|
|
2658
2844
|
replayLog.answers = intrabar.recorder.answers[c.i] ?? [];
|
|
@@ -2671,7 +2857,7 @@ function strategyEachBar(fn: (c: BarContext) => number | boolean | void): Series
|
|
|
2671
2857
|
varipState.mode = 'live';
|
|
2672
2858
|
varipState.scratch = null;
|
|
2673
2859
|
}
|
|
2674
|
-
});
|
|
2860
|
+
}, undefined, fn);
|
|
2675
2861
|
}
|
|
2676
2862
|
const recorder = scriptOptions.recorder;
|
|
2677
2863
|
// an incremental run keeps the engine state at the last confirmed bar: the engine has to save and restore it
|
|
@@ -2944,6 +3130,11 @@ export interface ChartContext {
|
|
|
2944
3130
|
* `request.security` merges on (#179), and the other fields its `syminfo.*` inside the expression.
|
|
2945
3131
|
*/
|
|
2946
3132
|
symbolInfo?: (symbol: string) => SymbolInfo | undefined;
|
|
3133
|
+
/**
|
|
3134
|
+
* Ticker of a seed data series for `request.seed(source, symbol, ...)` (#205), whose bars then come from
|
|
3135
|
+
* {@link bars} like any other symbol. Default: `"<SOURCE>:<SYMBOL>"` upper-cased.
|
|
3136
|
+
*/
|
|
3137
|
+
seedSymbol?: (source: string, symbol: string) => string;
|
|
2947
3138
|
}
|
|
2948
3139
|
|
|
2949
3140
|
/** Calendar and properties of a symbol, as in {@link ChartContext}. */
|
|
@@ -3386,8 +3577,9 @@ export const barstate = {
|
|
|
3386
3577
|
get isnew(): Series { return namedFlag('isnew', (i, n) => !lastRealtime(i, n) || chartCtx.lastBarNew !== false); },
|
|
3387
3578
|
get islastconfirmedhistory(): Series {
|
|
3388
3579
|
return namedFlag('islastconfirmedhistory', (i, n) => {
|
|
3389
|
-
// moves to the next bar with each new bar: not kept by an incremental run (#196)
|
|
3390
|
-
|
|
3580
|
+
// moves to the next bar with each new bar: not kept by an incremental run (#196), but the same in the intrabar
|
|
3581
|
+
// runs of a backtest (#206)
|
|
3582
|
+
if (!intrabarRun) incremental.nonIncremental('barstate.islastconfirmedhistory');
|
|
3391
3583
|
const lastConfirmed = chartCtx.lastBarConfirmed === true && chartCtx.realtime !== true;
|
|
3392
3584
|
const count = chartBarCount(n);
|
|
3393
3585
|
return i === (lastConfirmed ? count - 1 : count - 2);
|
|
@@ -3666,10 +3858,26 @@ function security_lower_tf<T extends SecurityValue>(
|
|
|
3666
3858
|
return (Array.isArray(result) ? mapped : mapped[0]) as T extends unknown[] ? number[][][] : number[][];
|
|
3667
3859
|
}
|
|
3668
3860
|
|
|
3669
|
-
/**
|
|
3861
|
+
/**
|
|
3862
|
+
* PineScript `request.seed(source, symbol, expression, ignore_invalid_symbol)` (#205): `expression` on a seed data
|
|
3863
|
+
* series, on the chart timeframe. The series is the symbol `ChartContext.seedSymbol(source, symbol)` (default
|
|
3864
|
+
* `"<SOURCE>:<SYMBOL>"` upper-cased), read as `request.security(<that symbol>, "", expression)`.
|
|
3865
|
+
*/
|
|
3866
|
+
function seed<T extends SecurityValue>(
|
|
3867
|
+
source: string,
|
|
3868
|
+
symbol: string,
|
|
3869
|
+
expression: () => T,
|
|
3870
|
+
ignore_invalid_symbol: boolean = false
|
|
3871
|
+
): T extends unknown[] ? Series[] : Series {
|
|
3872
|
+
const ticker = chartCtx.seedSymbol?.(source, symbol) ?? `${source.toUpperCase()}:${symbol.toUpperCase()}`;
|
|
3873
|
+
return security(ticker, '', expression, barmerge.gaps_off, barmerge.lookahead_off, ignore_invalid_symbol);
|
|
3874
|
+
}
|
|
3875
|
+
|
|
3876
|
+
/** PineScript `request.*`: `security` (issue #101, other symbols #179, lower timeframes #181), `security_lower_tf` and `seed` (#205). */
|
|
3670
3877
|
/** PineScript parameters of `request.security` / `request.security_lower_tf`, in their positional order. */
|
|
3671
3878
|
const SECURITY_PARAMETERS = ['symbol', 'timeframe', 'expression', 'gaps', 'lookahead', 'ignore_invalid_symbol', 'currency', 'calc_bars_count'] as const;
|
|
3672
3879
|
const SECURITY_LOWER_TF_PARAMETERS = ['symbol', 'timeframe', 'expression', 'ignore_invalid_symbol', 'currency', 'ignore_invalid_timeframe', 'calc_bars_count'] as const;
|
|
3880
|
+
const SEED_PARAMETERS = ['source', 'symbol', 'expression', 'ignore_invalid_symbol', 'calc_bars_count'] as const;
|
|
3673
3881
|
|
|
3674
3882
|
/** Named arguments of `request.security` (PineScript names). */
|
|
3675
3883
|
export interface SecurityArgs<T extends SecurityValue = SecurityValue> {
|
|
@@ -3727,7 +3935,28 @@ function securityLowerTfCall<T extends SecurityValue>(
|
|
|
3727
3935
|
return security_lower_tf(a[0] as string, a[1] as string, a[2] as () => T, a[3] as boolean | undefined);
|
|
3728
3936
|
}
|
|
3729
3937
|
|
|
3730
|
-
|
|
3938
|
+
/** Named arguments of `request.seed` (PineScript names). */
|
|
3939
|
+
export interface SeedArgs<T extends SecurityValue = SecurityValue> {
|
|
3940
|
+
source?: string;
|
|
3941
|
+
symbol?: string;
|
|
3942
|
+
expression?: () => T;
|
|
3943
|
+
ignore_invalid_symbol?: boolean;
|
|
3944
|
+
calc_bars_count?: number;
|
|
3945
|
+
}
|
|
3946
|
+
|
|
3947
|
+
/** `request.seed` with PineScript's named arguments. */
|
|
3948
|
+
function seedCall<T extends SecurityValue>(
|
|
3949
|
+
...args:
|
|
3950
|
+
| [source: string, symbol: string, expression: () => T, ignore_invalid_symbol?: boolean]
|
|
3951
|
+
| [source: string, symbol: string, expression: () => T, args: SeedArgs<T>]
|
|
3952
|
+
| [args: SeedArgs<T> & { source: string; symbol: string; expression: () => T }]
|
|
3953
|
+
): T extends unknown[] ? Series[] : Series {
|
|
3954
|
+
const a = namedArguments('request.seed', SEED_PARAMETERS, args);
|
|
3955
|
+
unsupportedSecurityArgs('request.seed', undefined, a[4]);
|
|
3956
|
+
return seed(a[0] as string, a[1] as string, a[2] as () => T, a[3] as boolean | undefined);
|
|
3957
|
+
}
|
|
3958
|
+
|
|
3959
|
+
export const request = strictNamespace('request', { security: securityCall, security_lower_tf: securityLowerTfCall, seed: seedCall });
|
|
3731
3960
|
|
|
3732
3961
|
// ── Drawing objects ──────────────────────────────────────────────────────────
|
|
3733
3962
|
// The drawing namespaces come from this bundle so that they share the registry that
|
|
@@ -4036,6 +4265,11 @@ void _saveRandom;
|
|
|
4036
4265
|
void _restoreRandom;
|
|
4037
4266
|
export const math = strictNamespace('math', {
|
|
4038
4267
|
...mathScript,
|
|
4268
|
+
// the generators start again on each run: a resumed run would draw other numbers (#206)
|
|
4269
|
+
random: ((min?: number, max?: number, seed?: number) => {
|
|
4270
|
+
incremental.nonIncremental('math.random');
|
|
4271
|
+
return mathCore.random(min, max, seed);
|
|
4272
|
+
}) as typeof mathCore.random,
|
|
4039
4273
|
round_to_mintick: ((number: number | Series, mintick?: number) => {
|
|
4040
4274
|
const tick = mintick ?? syminfo.mintick;
|
|
4041
4275
|
return number instanceof Series ? mathCore.round_to_mintick(number, tick) : mathCore.round_to_mintick(number, tick);
|