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/package.json
CHANGED
|
@@ -195,3 +195,19 @@ eachBar((c) => {
|
|
|
195
195
|
if (c.get(up) === 1) alert("Close " + str.tostring(c.close, "#.##") + " crossed above the SMA", alert.freq_once_per_bar_close);
|
|
196
196
|
});
|
|
197
197
|
```
|
|
198
|
+
|
|
199
|
+
## Logs
|
|
200
|
+
|
|
201
|
+
- `log.info(message, ...args)`, `log.warning(...)`, `log.error(...)`: a message in the host's logs panel. Inside a bar
|
|
202
|
+
loop it is made on that bar; at the top level, on every bar. With arguments, `message` is a `str.format()` pattern
|
|
203
|
+
and a Series argument gives its value on the bar. The messages of a run are in `result.logs` (bar, time, level,
|
|
204
|
+
message, and the script line when the host resolves it with `setLogLineResolver`), by bar, the newest 10,000.
|
|
205
|
+
|
|
206
|
+
```js
|
|
207
|
+
indicator("Logs");
|
|
208
|
+
const ma = ta.sma(close, 20);
|
|
209
|
+
eachBar((c) => {
|
|
210
|
+
if (c.i === c.n - 1) log.info("Last close {0}, SMA {1}", c.close, c.get(ma));
|
|
211
|
+
if (c.volume === 0) log.warning("No volume on bar {0}", c.i);
|
|
212
|
+
});
|
|
213
|
+
```
|
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.18.0';
|
|
236
236
|
|
|
237
237
|
/**
|
|
238
238
|
* Library information
|
package/src/script/globals.ts
CHANGED
|
@@ -99,6 +99,9 @@ declare global {
|
|
|
99
99
|
const text: typeof S.text;
|
|
100
100
|
const chart: typeof S.chart;
|
|
101
101
|
const alert: typeof S.alert;
|
|
102
|
+
const log: typeof S.log;
|
|
103
|
+
const MAX_LOG_ENTRIES: typeof S.MAX_LOG_ENTRIES;
|
|
104
|
+
const setLogLineResolver: typeof S.setLogLineResolver;
|
|
102
105
|
const Series: typeof S.Series;
|
|
103
106
|
const BarData: typeof S.BarData;
|
|
104
107
|
const na: typeof S.na;
|
|
@@ -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
|
@@ -195,7 +195,7 @@ export interface ScriptRunResult {
|
|
|
195
195
|
* last bar. `outputValues`: per plotshape() / plotchar() / plotarrow() id, the value of its series on each bar where
|
|
196
196
|
* it is not na (a condition gives 1 or 0), at the bar it was computed on (the offset not applied).
|
|
197
197
|
*/
|
|
198
|
-
result: IndicatorResult & { alerts?: AlertState[]; alertCalls?: AlertCall[]; outputValues?: Record<string, TimeValue[]
|
|
198
|
+
result: IndicatorResult & { alerts?: AlertState[]; alertCalls?: AlertCall[]; outputValues?: Record<string, TimeValue[]>; logs?: LogEntry[] };
|
|
199
199
|
/** The script called alert() during the run (PineScript `hasAlertFunction` is known at compile time: a host that
|
|
200
200
|
* needs it before any bar runs reads the source). */
|
|
201
201
|
hasAlertFunction: boolean;
|
|
@@ -274,6 +274,8 @@ interface Collector {
|
|
|
274
274
|
alertConfig: AlertConditionConfig[];
|
|
275
275
|
alerts: AlertState[];
|
|
276
276
|
alertCalls: AlertCall[];
|
|
277
|
+
/** log.*() messages of the run. */
|
|
278
|
+
logs: LogEntry[];
|
|
277
279
|
hasAlertFunction: boolean;
|
|
278
280
|
strategy?: StrategyRun;
|
|
279
281
|
}
|
|
@@ -332,6 +334,7 @@ function freshCollector(inputValues: Record<string, unknown>): Collector {
|
|
|
332
334
|
alertConfig: [],
|
|
333
335
|
alerts: [],
|
|
334
336
|
alertCalls: [],
|
|
337
|
+
logs: [],
|
|
335
338
|
hasAlertFunction: false,
|
|
336
339
|
};
|
|
337
340
|
}
|
|
@@ -396,6 +399,13 @@ export class StrategyRecorder {
|
|
|
396
399
|
readonly varipStarts: unknown[][] = [];
|
|
397
400
|
/** Current `varip` values: kept through the intrabar runs (no rollback). */
|
|
398
401
|
readonly varip: unknown[] = [];
|
|
402
|
+
/**
|
|
403
|
+
* Why the intrabar runs of this recorder calculate all the bars before their bar (a feature that is not resumed,
|
|
404
|
+
* or a verification difference); null while they are resumed (see {@link executeIntrabar}).
|
|
405
|
+
*/
|
|
406
|
+
get intrabarFullRunReason(): string | null {
|
|
407
|
+
return intrabarChains.get(this)?.reason ?? null;
|
|
408
|
+
}
|
|
399
409
|
}
|
|
400
410
|
|
|
401
411
|
/** Module state of a run, saved around a nested run (an intrabar run inside the bar loop of the main run). */
|
|
@@ -474,6 +484,8 @@ function runBody(
|
|
|
474
484
|
): ScriptRunResult {
|
|
475
485
|
// A run inside another one (an intrabar run of a strategy) puts the outer run back when it ends.
|
|
476
486
|
const outer = ctx ? saveRunState() : null;
|
|
487
|
+
// A main run with a recorder starts a new backtest: its intrabar runs start again (#206).
|
|
488
|
+
if (options.recorder) intrabarChains.delete(options.recorder);
|
|
477
489
|
// A plain run inside an incremental one is not part of it.
|
|
478
490
|
const outerInc = inc ? incremental.beginRun(inc) : incremental.suspendRun();
|
|
479
491
|
ctxBars.setAll(barsInput);
|
|
@@ -529,6 +541,8 @@ function runBody(
|
|
|
529
541
|
...(intrabarRun ? {} : drawingOutputs(ctxBars.bars, chartCtx.timeUnit)),
|
|
530
542
|
alerts: c.alerts.length ? c.alerts : undefined,
|
|
531
543
|
alertCalls: c.alertCalls.length ? c.alertCalls : undefined,
|
|
544
|
+
// By bar, in call order on each bar (the top-level calls make theirs on every bar at once).
|
|
545
|
+
logs: c.logs.length ? [...c.logs].sort((x, y) => x.bar - y.bar).slice(-MAX_LOG_ENTRIES) : undefined,
|
|
532
546
|
},
|
|
533
547
|
hasAlertFunction: c.hasAlertFunction,
|
|
534
548
|
};
|
|
@@ -549,18 +563,101 @@ export interface IntrabarOptions {
|
|
|
549
563
|
engine: StrategyEngine;
|
|
550
564
|
/** The recorder of the main run. */
|
|
551
565
|
recorder: StrategyRecorder;
|
|
566
|
+
/**
|
|
567
|
+
* Resume the run from the state at the start of the bar (default true, #206); false calculates all the bars before
|
|
568
|
+
* it, as before.
|
|
569
|
+
*/
|
|
570
|
+
resume?: boolean;
|
|
571
|
+
/**
|
|
572
|
+
* Resumed runs also calculated in full and compared, the first ones of a backtest (default 2): a difference makes the
|
|
573
|
+
* next intrabar runs full ones (a script that keeps state outside persist() boxes).
|
|
574
|
+
*/
|
|
575
|
+
verify?: number;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** What {@link executeIntrabar} calculated. */
|
|
579
|
+
export interface IntrabarUpdate {
|
|
580
|
+
/** First bar calculated: 0 for a full run, else the bar of the previous intrabar run (#206) */
|
|
581
|
+
from: number;
|
|
582
|
+
/** The run was resumed from the state of the bar before `from` */
|
|
583
|
+
incremental: boolean;
|
|
584
|
+
/** Why the intrabar runs of the backtest are full runs (null: resumed) */
|
|
585
|
+
fullRunReason: string | null;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** The intrabar runs of a backtest (one recorder): each one resumes from the state the previous one kept (#206). */
|
|
589
|
+
interface IntrabarChain {
|
|
590
|
+
body: () => void;
|
|
591
|
+
inputs: Record<string, unknown>;
|
|
592
|
+
chart: ChartContext;
|
|
593
|
+
engine: StrategyEngine;
|
|
594
|
+
lastBarIndex: number;
|
|
595
|
+
/** State kept by the last run (null: the next run is a full one that records it) */
|
|
596
|
+
memory: incremental.RunMemory | null;
|
|
597
|
+
/** Bars of the last run */
|
|
598
|
+
n: number;
|
|
599
|
+
reason: string | null;
|
|
600
|
+
verifyLeft: number;
|
|
601
|
+
}
|
|
602
|
+
const intrabarChains = new WeakMap<StrategyRecorder, IntrabarChain>();
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* The live engine of an intrabar run with its calls logged (`log`, to compare two runs) and its order calls, when
|
|
606
|
+
* `writes` is given, kept there instead of made (a resumed run gives them to the engine once it has ended: a run
|
|
607
|
+
* stopped in the middle makes none).
|
|
608
|
+
*/
|
|
609
|
+
function intrabarEngine(engine: StrategyEngine, log: unknown[] | null, writes: Array<() => void> | null): StrategyEngine {
|
|
610
|
+
const read = <T>(name: string, args: unknown[], value: T): T => {
|
|
611
|
+
log?.push([name, ...args, value]);
|
|
612
|
+
return value;
|
|
613
|
+
};
|
|
614
|
+
const write = (name: string, args: unknown[], call: () => void): void => {
|
|
615
|
+
log?.push([name, ...args]);
|
|
616
|
+
if (writes) writes.push(call);
|
|
617
|
+
else call();
|
|
618
|
+
};
|
|
619
|
+
return {
|
|
620
|
+
...forward(engine),
|
|
621
|
+
entry: (id, direction, options) => write('entry', [id, direction, options], () => engine.entry(id, direction, options)),
|
|
622
|
+
order: (id, direction, options) => write('order', [id, direction, options], () => engine.order(id, direction, options)),
|
|
623
|
+
exit: (id, options) => write('exit', [id, options], () => engine.exit(id, options)),
|
|
624
|
+
close: (id, options) => write('close', [id, options], () => engine.close(id, options)),
|
|
625
|
+
close_all: (options) => write('close_all', [options], () => engine.close_all(options)),
|
|
626
|
+
cancel: (id) => write('cancel', [id], () => engine.cancel(id)),
|
|
627
|
+
cancel_all: () => write('cancel_all', [], () => engine.cancel_all()),
|
|
628
|
+
get: (name) => read('get', [name], engine.get(name)),
|
|
629
|
+
openTrade: (index) => read('openTrade', [index], engine.openTrade(index)),
|
|
630
|
+
closedTrade: (index) => read('closedTrade', [index], engine.closedTrade(index)),
|
|
631
|
+
defaultEntryQty: engine.defaultEntryQty
|
|
632
|
+
? (price) => read('defaultEntryQty', [price], engine.defaultEntryQty!(price))
|
|
633
|
+
: undefined,
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** Puts the `varip` values back to a copy taken before a run. */
|
|
638
|
+
function setVarip(recorder: StrategyRecorder, values: unknown[]): void {
|
|
639
|
+
recorder.varip.length = 0;
|
|
640
|
+
recorder.varip.push(...values);
|
|
552
641
|
}
|
|
553
642
|
|
|
554
643
|
/**
|
|
555
644
|
* Runs a strategy once more on a bar, inside the bar (PineScript `calc_on_order_fills` and calculations on the
|
|
556
645
|
* 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
|
-
*
|
|
646
|
+
* the tick price, its high and low the extremes reached so far). The script's variables come back to their state at
|
|
647
|
+
* the start of the bar (PineScript rollback), except `varip` ones. In strategy.eachBar(), the bars before replay the
|
|
648
|
+
* engine's answers that the main run recorded (their order calls are dropped), and the bar itself calls
|
|
649
|
+
* `options.engine` without processBar / processClose (the host is filling its orders). That bar is a confirmed
|
|
650
|
+
* history bar (`barstate.isconfirmed`); `barstate.islast`, `last_bar_index` and `BarContext.n` keep the chart's last
|
|
651
|
+
* bar. Strategy risk rules are not declared again, and the outputs (plots, drawings) are dropped. Re-entrant: the host
|
|
652
|
+
* calls it inside the bar loop of the main run.
|
|
653
|
+
*
|
|
654
|
+
* Resumed runs (#206): the intrabar runs of a backtest (same recorder, script, inputs, chart and engine) keep the state
|
|
655
|
+
* of the script as createScriptRun does, so a run calculates its bar only (and the bars since the previous intrabar
|
|
656
|
+
* run), not all the bars before it; the order calls and `strategy.*` reads are the same as in a full run. The bars
|
|
657
|
+
* before `options.bar` must be the main run's (the same on every call). A script that keeps state outside `persist()`
|
|
658
|
+
* boxes (a `let` variable outside the callbacks that a callback changes), or uses a feature that is not resumed, gets
|
|
659
|
+
* full runs (`fullRunReason`); the first resumed runs are also calculated in full and compared (`verify`). A resumed
|
|
660
|
+
* run gives its order calls to the engine once it has ended.
|
|
564
661
|
*/
|
|
565
662
|
export function executeIntrabar(
|
|
566
663
|
body: () => void,
|
|
@@ -568,25 +665,130 @@ export function executeIntrabar(
|
|
|
568
665
|
inputs: Record<string, unknown>,
|
|
569
666
|
chart: ChartContext,
|
|
570
667
|
options: IntrabarOptions
|
|
571
|
-
):
|
|
572
|
-
const
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
668
|
+
): IntrabarUpdate {
|
|
669
|
+
const recorder = options.recorder;
|
|
670
|
+
// History bars are confirmed, also on their ticks (the reference app: a barstate.isconfirmed entry fills on them).
|
|
671
|
+
const runChart: ChartContext = { ...chart, lastBarConfirmed: true, realtime: false };
|
|
672
|
+
const execute = (engine: StrategyEngine, inc: incremental.ActiveRun | null): void => {
|
|
673
|
+
const run: IntrabarRun = { bar: options.bar, lastBarIndex: options.lastBarIndex, engine, recorder };
|
|
674
|
+
runBody(
|
|
675
|
+
() => {
|
|
676
|
+
intrabarRun = run;
|
|
677
|
+
varipRun = { slot: 0, recorder, mode: 'live', scratch: null };
|
|
678
|
+
body();
|
|
679
|
+
},
|
|
680
|
+
bars,
|
|
681
|
+
inputs,
|
|
682
|
+
runChart,
|
|
683
|
+
{ strategyEngine: () => engine },
|
|
684
|
+
inc
|
|
685
|
+
);
|
|
686
|
+
};
|
|
687
|
+
const fullRun = (reason: string | null): IntrabarUpdate => {
|
|
688
|
+
execute(options.engine, null);
|
|
689
|
+
return { from: 0, incremental: false, fullRunReason: reason };
|
|
690
|
+
};
|
|
691
|
+
if (options.resume === false) return fullRun('resume: false');
|
|
692
|
+
const n = bars.length;
|
|
693
|
+
if (options.bar !== n - 1) return fullRun('the bar is not the last of the bars');
|
|
694
|
+
|
|
695
|
+
let chain = intrabarChains.get(recorder);
|
|
696
|
+
if (
|
|
697
|
+
!chain || chain.body !== body || chain.engine !== options.engine || chain.lastBarIndex !== options.lastBarIndex ||
|
|
698
|
+
!sameResult(chain.inputs, inputs) || !sameChart(chain.chart, runChart)
|
|
699
|
+
) {
|
|
700
|
+
chain = {
|
|
701
|
+
body,
|
|
702
|
+
inputs,
|
|
703
|
+
chart: runChart,
|
|
704
|
+
engine: options.engine,
|
|
705
|
+
lastBarIndex: options.lastBarIndex,
|
|
706
|
+
memory: null,
|
|
707
|
+
n: 0,
|
|
708
|
+
reason: null,
|
|
709
|
+
verifyLeft: options.verify ?? 2,
|
|
710
|
+
};
|
|
711
|
+
intrabarChains.set(recorder, chain);
|
|
712
|
+
}
|
|
713
|
+
if (chain.reason) return fullRun(chain.reason);
|
|
714
|
+
|
|
715
|
+
const memory = chain.memory;
|
|
716
|
+
// A resumed run changes the memory in place: it is usable again only when the run has ended.
|
|
717
|
+
chain.memory = null;
|
|
718
|
+
if (!memory || n < chain.n) {
|
|
719
|
+
const inc = newActiveRun('record', bars, 0, null);
|
|
720
|
+
execute(options.engine, inc);
|
|
721
|
+
if (inc.blocked) chain.reason = inc.blocked;
|
|
722
|
+
else {
|
|
723
|
+
chain.memory = inc.next;
|
|
724
|
+
chain.n = n;
|
|
725
|
+
}
|
|
726
|
+
return { from: 0, incremental: false, fullRunReason: chain.reason };
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
const from = chain.n - 1;
|
|
730
|
+
const start = incremental.plainCopy(recorder.varip);
|
|
731
|
+
if (start === incremental.NOT_COPIED) {
|
|
732
|
+
chain.reason = 'a varip value that is not plain data';
|
|
733
|
+
return fullRun(chain.reason);
|
|
734
|
+
}
|
|
735
|
+
const verifying = chain.verifyLeft > 0;
|
|
736
|
+
const log: unknown[] | null = verifying ? [] : null;
|
|
737
|
+
const writes: Array<() => void> = [];
|
|
738
|
+
const inc = newActiveRun('resume', bars, from, memory);
|
|
739
|
+
try {
|
|
740
|
+
execute(intrabarEngine(options.engine, log, writes), inc);
|
|
741
|
+
} catch (err) {
|
|
742
|
+
// The run is calculated in full instead: the varip values back to the start, the kept order calls dropped. An
|
|
743
|
+
// error of the script is the full run's (it throws it again).
|
|
744
|
+
setVarip(recorder, start as unknown[]);
|
|
745
|
+
if (err instanceof incremental.ResumeAborted) chain.reason = err.reason;
|
|
746
|
+
return fullRun(chain.reason);
|
|
747
|
+
}
|
|
748
|
+
if (verifying) {
|
|
749
|
+
chain.verifyLeft--;
|
|
750
|
+
const resumedVarip = incremental.plainCopy(recorder.varip);
|
|
751
|
+
setVarip(recorder, start as unknown[]);
|
|
752
|
+
const fullLog: unknown[] = [];
|
|
753
|
+
execute(intrabarEngine(options.engine, fullLog, null), null);
|
|
754
|
+
if (resumedVarip === incremental.NOT_COPIED || !sameResult(log, fullLog) || !sameResult(resumedVarip, recorder.varip)) {
|
|
755
|
+
chain.reason = 'a resumed intrabar run differs from a full run (state kept outside persist()?)';
|
|
756
|
+
return { from: 0, incremental: false, fullRunReason: chain.reason };
|
|
757
|
+
}
|
|
758
|
+
} else {
|
|
759
|
+
for (const call of writes) call();
|
|
760
|
+
}
|
|
761
|
+
chain.memory = inc.next;
|
|
762
|
+
chain.n = n;
|
|
763
|
+
return { from, incremental: true, fullRunReason: null };
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/** The state of an incremental run: a recorded one (full), or one resumed at bar `from` from `prev`. */
|
|
767
|
+
function newActiveRun(
|
|
768
|
+
mode: 'record' | 'resume',
|
|
769
|
+
b: Bar[],
|
|
770
|
+
from: number,
|
|
771
|
+
prev: incremental.RunMemory | null
|
|
772
|
+
): incremental.ActiveRun {
|
|
773
|
+
const next = incremental.emptyMemory(b.length);
|
|
774
|
+
// the block that draws stays the one of the previous run (the forming bar may not draw)
|
|
775
|
+
if (mode === 'resume' && prev) next.drawingBlock = prev.drawingBlock;
|
|
776
|
+
return {
|
|
777
|
+
mode,
|
|
778
|
+
from,
|
|
779
|
+
bars: b,
|
|
780
|
+
prev: mode === 'resume' ? prev : null,
|
|
781
|
+
next,
|
|
782
|
+
seriesSlot: 0,
|
|
783
|
+
taSlot: 0,
|
|
784
|
+
blockSlot: 0,
|
|
785
|
+
plotSlot: 0,
|
|
786
|
+
boxSlot: 0,
|
|
787
|
+
drawSlot: 0,
|
|
788
|
+
block: -1,
|
|
789
|
+
boxes: [],
|
|
790
|
+
blocked: null,
|
|
577
791
|
};
|
|
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
792
|
}
|
|
591
793
|
|
|
592
794
|
// ── Incremental runs (#196) ──────────────────────────────────────────────────
|
|
@@ -715,28 +917,11 @@ export function createScriptRun(
|
|
|
715
917
|
let previousChart: ChartContext = chart;
|
|
716
918
|
let reason: string | null = null;
|
|
717
919
|
let verifyLeft = options.verify ?? 2;
|
|
920
|
+
/** The log messages of the last update: a resumed update keeps those of the bars it does not calculate again. */
|
|
921
|
+
let lastLogs: LogEntry[] | undefined;
|
|
718
922
|
|
|
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
|
-
};
|
|
923
|
+
const newRun = (mode: 'record' | 'resume', b: Bar[], from: number): incremental.ActiveRun =>
|
|
924
|
+
newActiveRun(mode, b, from, memory);
|
|
740
925
|
|
|
741
926
|
const full = (b: Bar[], c: ChartContext): ScriptRunUpdate => {
|
|
742
927
|
memory = null;
|
|
@@ -768,6 +953,7 @@ export function createScriptRun(
|
|
|
768
953
|
let result: ScriptRunResult | null = null;
|
|
769
954
|
try {
|
|
770
955
|
result = runBody(body, b, inputs, c, options, inc);
|
|
956
|
+
result.result.logs = resumedLogs(lastLogs, result.result.logs, from);
|
|
771
957
|
} catch (err) {
|
|
772
958
|
// the memory is changed in place by a resumed run: an error leaves it unusable
|
|
773
959
|
memory = null;
|
|
@@ -792,6 +978,7 @@ export function createScriptRun(
|
|
|
792
978
|
}
|
|
793
979
|
}
|
|
794
980
|
previous = out.incremental && last ? copyBars(b, last, last.n - 1) : copyBars(b);
|
|
981
|
+
lastLogs = out.result.logs;
|
|
795
982
|
return out;
|
|
796
983
|
},
|
|
797
984
|
};
|
|
@@ -823,7 +1010,8 @@ export interface VaripVariable<T> {
|
|
|
823
1010
|
*/
|
|
824
1011
|
export function varip<T>(initial: T): VaripVariable<T> {
|
|
825
1012
|
collector();
|
|
826
|
-
|
|
1013
|
+
// the intrabar runs of a backtest resume with varip values read in strategy.eachBar() (#206)
|
|
1014
|
+
if (!intrabarRun) incremental.nonIncremental('varip');
|
|
827
1015
|
const slot = varipRun.slot++;
|
|
828
1016
|
const state = varipRun;
|
|
829
1017
|
const rec = state.recorder;
|
|
@@ -839,7 +1027,11 @@ export function varip<T>(initial: T): VaripVariable<T> {
|
|
|
839
1027
|
};
|
|
840
1028
|
}
|
|
841
1029
|
if (rec.varip.length <= slot) rec.varip[slot] = initial;
|
|
842
|
-
const store = (): unknown[] =>
|
|
1030
|
+
const store = (): unknown[] => {
|
|
1031
|
+
// elsewhere, a resumed run would keep values of the bars before calculated with older varip values
|
|
1032
|
+
if (incremental.active && !ctx?.strategy?.inLoop) incremental.nonIncremental('varip used outside strategy.eachBar()');
|
|
1033
|
+
return state.mode === 'replay' && state.scratch ? state.scratch : rec.varip;
|
|
1034
|
+
};
|
|
843
1035
|
return {
|
|
844
1036
|
get value() {
|
|
845
1037
|
return store()[slot] as T;
|
|
@@ -1173,9 +1365,10 @@ export const bar_index = new Series(ctxBars, (_b, i) => i);
|
|
|
1173
1365
|
bar_index.fullHistory = true;
|
|
1174
1366
|
/** PineScript `last_bar_index`: the index of the last bar, on every bar. In a bar loop, `c.n - 1`. */
|
|
1175
1367
|
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
|
-
|
|
1368
|
+
// the same value on every bar, changed by a new bar: not kept by an incremental run (#196), but the same in the
|
|
1369
|
+
// intrabar runs of a backtest (the chart's last bar, #206)
|
|
1370
|
+
if (!intrabarRun) incremental.nonIncremental('last_bar_index');
|
|
1371
|
+
return chartBarCount(data.length) - 1;
|
|
1179
1372
|
});
|
|
1180
1373
|
last_bar_index.fullHistory = true;
|
|
1181
1374
|
// built-in price variables keep the whole history (no 5000-bar limit)
|
|
@@ -2400,7 +2593,7 @@ function runBlock(
|
|
|
2400
2593
|
const b = bars();
|
|
2401
2594
|
// An intrabar run ends on its bar: the chart's last bar stays the main run's.
|
|
2402
2595
|
const lastIndex = intrabarRun ? intrabarRun.lastBarIndex : b.length - 1;
|
|
2403
|
-
let out: number[] =
|
|
2596
|
+
let out: number[] = [];
|
|
2404
2597
|
const cache = new Map<Series, number[]>();
|
|
2405
2598
|
// history buffers by source: the slot of a Series made by the script (matched across incremental runs), or the Series
|
|
2406
2599
|
const buffers = new Map<unknown, HistoryBuffer>();
|
|
@@ -2420,7 +2613,8 @@ function runBlock(
|
|
|
2420
2613
|
}
|
|
2421
2614
|
let start = 0;
|
|
2422
2615
|
let checkpoint: incremental.BlockCheckpoint | null = null;
|
|
2423
|
-
if (run?.mode
|
|
2616
|
+
if (run?.mode !== 'resume') out = new Array(b.length).fill(NaN);
|
|
2617
|
+
else {
|
|
2424
2618
|
const prev = run.prev?.blocks[slot];
|
|
2425
2619
|
if (!prev) incremental.nonIncremental('a new eachBar() block');
|
|
2426
2620
|
start = run.from;
|
|
@@ -2464,8 +2658,9 @@ function runBlock(
|
|
|
2464
2658
|
return idx;
|
|
2465
2659
|
},
|
|
2466
2660
|
get n() {
|
|
2467
|
-
// the bar count changes with each new bar: a value read from it is not kept by an incremental run
|
|
2468
|
-
|
|
2661
|
+
// the bar count changes with each new bar: a value read from it is not kept by an incremental run (the chart's
|
|
2662
|
+
// last bar of the intrabar runs of a backtest does not change)
|
|
2663
|
+
if (run && !intrabarRun) incremental.nonIncremental('BarContext.n');
|
|
2469
2664
|
return lastIndex + 1;
|
|
2470
2665
|
},
|
|
2471
2666
|
get time() {
|
|
@@ -2652,7 +2847,7 @@ function strategyEachBar(fn: (c: BarContext) => number | boolean | void): Series
|
|
|
2652
2847
|
const varipState = varipRun;
|
|
2653
2848
|
const replayLog: { answers: readonly unknown[]; next: number } = { answers: [], next: 0 };
|
|
2654
2849
|
const replayed = replayEngine(replayLog);
|
|
2655
|
-
return
|
|
2850
|
+
return runBlock((c) => {
|
|
2656
2851
|
const replay = c.i < intrabar.bar;
|
|
2657
2852
|
if (replay) {
|
|
2658
2853
|
replayLog.answers = intrabar.recorder.answers[c.i] ?? [];
|
|
@@ -2671,7 +2866,7 @@ function strategyEachBar(fn: (c: BarContext) => number | boolean | void): Series
|
|
|
2671
2866
|
varipState.mode = 'live';
|
|
2672
2867
|
varipState.scratch = null;
|
|
2673
2868
|
}
|
|
2674
|
-
});
|
|
2869
|
+
}, undefined, fn);
|
|
2675
2870
|
}
|
|
2676
2871
|
const recorder = scriptOptions.recorder;
|
|
2677
2872
|
// an incremental run keeps the engine state at the last confirmed bar: the engine has to save and restore it
|
|
@@ -3391,8 +3586,9 @@ export const barstate = {
|
|
|
3391
3586
|
get isnew(): Series { return namedFlag('isnew', (i, n) => !lastRealtime(i, n) || chartCtx.lastBarNew !== false); },
|
|
3392
3587
|
get islastconfirmedhistory(): Series {
|
|
3393
3588
|
return namedFlag('islastconfirmedhistory', (i, n) => {
|
|
3394
|
-
// moves to the next bar with each new bar: not kept by an incremental run (#196)
|
|
3395
|
-
|
|
3589
|
+
// moves to the next bar with each new bar: not kept by an incremental run (#196), but the same in the intrabar
|
|
3590
|
+
// runs of a backtest (#206)
|
|
3591
|
+
if (!intrabarRun) incremental.nonIncremental('barstate.islastconfirmedhistory');
|
|
3396
3592
|
const lastConfirmed = chartCtx.lastBarConfirmed === true && chartCtx.realtime !== true;
|
|
3397
3593
|
const count = chartBarCount(n);
|
|
3398
3594
|
return i === (lastConfirmed ? count - 1 : count - 2);
|
|
@@ -4047,6 +4243,84 @@ export const alert = Object.assign(alertImpl, {
|
|
|
4047
4243
|
freq_once_per_bar_close: 'once_per_bar_close',
|
|
4048
4244
|
} as const);
|
|
4049
4245
|
|
|
4246
|
+
// ── Logs (log.info / log.warning / log.error) ────────────────────────────────
|
|
4247
|
+
|
|
4248
|
+
/** The level of a log message. */
|
|
4249
|
+
export type LogLevel = 'info' | 'warning' | 'error';
|
|
4250
|
+
|
|
4251
|
+
/** One log.*() message: the bar it was made on (index, and time as given in the input bars), its level and text, and
|
|
4252
|
+
* the line of the script that made it when the host resolves it ({@link setLogLineResolver}). */
|
|
4253
|
+
export interface LogEntry {
|
|
4254
|
+
bar: number;
|
|
4255
|
+
time: number;
|
|
4256
|
+
level: LogLevel;
|
|
4257
|
+
message: string;
|
|
4258
|
+
line?: number;
|
|
4259
|
+
}
|
|
4260
|
+
|
|
4261
|
+
/** The most messages a run keeps: the newest ones. */
|
|
4262
|
+
export const MAX_LOG_ENTRIES = 10_000;
|
|
4263
|
+
|
|
4264
|
+
let logLineResolver: ((stack: string) => number | undefined) | null = null;
|
|
4265
|
+
|
|
4266
|
+
/**
|
|
4267
|
+
* How the host finds the line of the script that called log.*(): `resolver` gets the stack of the call (an Error's
|
|
4268
|
+
* `stack`) and gives the line in the script's own source. Null (the default): messages have no line.
|
|
4269
|
+
*/
|
|
4270
|
+
export function setLogLineResolver(resolver: ((stack: string) => number | undefined) | null): void {
|
|
4271
|
+
logLineResolver = resolver;
|
|
4272
|
+
}
|
|
4273
|
+
|
|
4274
|
+
function logImpl(level: LogLevel, message: string | ReadonlyArray<string | undefined>, args: unknown[]): void {
|
|
4275
|
+
const c = collector();
|
|
4276
|
+
const b = ctxBars.bars;
|
|
4277
|
+
const line = logLineResolver ? logLineResolver(new Error().stack ?? '') : undefined;
|
|
4278
|
+
const add = (i: number): void => {
|
|
4279
|
+
const text = typeof message === 'string' ? message : message[i];
|
|
4280
|
+
if (text === undefined || text === null) return;
|
|
4281
|
+
// A Series argument gives its value on the bar.
|
|
4282
|
+
const values = args.map((a) => (a instanceof Series ? a.get(i) : a));
|
|
4283
|
+
const entry: LogEntry = {
|
|
4284
|
+
bar: i,
|
|
4285
|
+
time: b[i]!.time as number,
|
|
4286
|
+
level,
|
|
4287
|
+
message: args.length ? formatMessage(String(text), values, exchangeTimezone) : String(text),
|
|
4288
|
+
};
|
|
4289
|
+
if (line !== undefined) entry.line = line;
|
|
4290
|
+
c.logs.push(entry);
|
|
4291
|
+
};
|
|
4292
|
+
if (currentBar >= 0) add(currentBar);
|
|
4293
|
+
else for (let i = 0; i < b.length; i++) add(i);
|
|
4294
|
+
if (c.logs.length > MAX_LOG_ENTRIES * 2) c.logs.splice(0, c.logs.length - MAX_LOG_ENTRIES);
|
|
4295
|
+
}
|
|
4296
|
+
|
|
4297
|
+
/**
|
|
4298
|
+
* PineScript `log.info()`, `log.warning()` and `log.error()`: a message for the host's logs panel, made on the current
|
|
4299
|
+
* bar inside eachBar() / strategy.eachBar(), on every bar at the top level of the script (which PineScript runs on
|
|
4300
|
+
* every bar; `message` is then a text or one text per bar, a bar whose text is na makes no message). With arguments,
|
|
4301
|
+
* `message` is a str.format() pattern (`log.info('close {0}', close)`), a Series argument giving its value on the bar.
|
|
4302
|
+
* The messages of a run are in `result.logs`, by bar ({@link MAX_LOG_ENTRIES} newest kept).
|
|
4303
|
+
*/
|
|
4304
|
+
export const log = strictNamespace('log', {
|
|
4305
|
+
info(message: string | ReadonlyArray<string | undefined>, ...args: unknown[]): void {
|
|
4306
|
+
logImpl('info', message, args);
|
|
4307
|
+
},
|
|
4308
|
+
warning(message: string | ReadonlyArray<string | undefined>, ...args: unknown[]): void {
|
|
4309
|
+
logImpl('warning', message, args);
|
|
4310
|
+
},
|
|
4311
|
+
error(message: string | ReadonlyArray<string | undefined>, ...args: unknown[]): void {
|
|
4312
|
+
logImpl('error', message, args);
|
|
4313
|
+
},
|
|
4314
|
+
});
|
|
4315
|
+
|
|
4316
|
+
/** The messages of a resumed run calculated from bar `from`: those of the run before on the bars before `from`, then the
|
|
4317
|
+
* new ones on the bars from `from` (the top-level log calls of a resumed run make them again on every bar). */
|
|
4318
|
+
function resumedLogs(before: LogEntry[] | undefined, now: LogEntry[] | undefined, from: number): LogEntry[] | undefined {
|
|
4319
|
+
const kept = (before ?? []).filter((e) => e.bar < from);
|
|
4320
|
+
const logs = kept.concat((now ?? []).filter((e) => e.bar >= from));
|
|
4321
|
+
return logs.length ? logs.slice(-MAX_LOG_ENTRIES) : undefined;
|
|
4322
|
+
}
|
|
4323
|
+
|
|
4050
4324
|
// ── Convenience re-exports ───────────────────────────────────────────────────
|
|
4051
4325
|
|
|
4052
4326
|
export { Series, BarData };
|
|
@@ -4078,6 +4352,11 @@ void _saveRandom;
|
|
|
4078
4352
|
void _restoreRandom;
|
|
4079
4353
|
export const math = strictNamespace('math', {
|
|
4080
4354
|
...mathScript,
|
|
4355
|
+
// the generators start again on each run: a resumed run would draw other numbers (#206)
|
|
4356
|
+
random: ((min?: number, max?: number, seed?: number) => {
|
|
4357
|
+
incremental.nonIncremental('math.random');
|
|
4358
|
+
return mathCore.random(min, max, seed);
|
|
4359
|
+
}) as typeof mathCore.random,
|
|
4081
4360
|
round_to_mintick: ((number: number | Series, mintick?: number) => {
|
|
4082
4361
|
const tick = mintick ?? syminfo.mintick;
|
|
4083
4362
|
return number instanceof Series ? mathCore.round_to_mintick(number, tick) : mathCore.round_to_mintick(number, tick);
|