oakscriptjs 0.19.0 → 0.21.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/box/index.d.ts +3 -3
- package/dist/cjs/box/index.d.ts.map +1 -1
- package/dist/cjs/box/index.js.map +2 -2
- package/dist/cjs/check/harness.d.ts.map +1 -1
- package/dist/cjs/check/harness.js +35 -1
- package/dist/cjs/check/harness.js.map +2 -2
- package/dist/cjs/drawing/output.d.ts +2 -1
- package/dist/cjs/drawing/output.d.ts.map +1 -1
- package/dist/cjs/drawing/output.js +5 -4
- package/dist/cjs/drawing/output.js.map +2 -2
- 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/label/index.d.ts +2 -2
- package/dist/cjs/label/index.d.ts.map +1 -1
- package/dist/cjs/label/index.js.map +2 -2
- package/dist/cjs/line/index.d.ts +4 -4
- package/dist/cjs/line/index.d.ts.map +1 -1
- package/dist/cjs/line/index.js +1 -1
- package/dist/cjs/line/index.js.map +2 -2
- package/dist/cjs/polyline/index.d.ts +2 -2
- package/dist/cjs/polyline/index.d.ts.map +1 -1
- package/dist/cjs/polyline/index.js.map +2 -2
- package/dist/cjs/script/constants.d.ts +6 -1
- package/dist/cjs/script/constants.d.ts.map +1 -1
- package/dist/cjs/script/constants.js +2 -1
- package/dist/cjs/script/constants.js.map +2 -2
- 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/index.d.ts +255 -28
- package/dist/cjs/script/index.d.ts.map +1 -1
- package/dist/cjs/script/index.js +349 -34
- package/dist/cjs/script/index.js.map +3 -3
- package/dist/cjs/security/events.d.ts +16 -0
- package/dist/cjs/security/events.d.ts.map +1 -0
- package/dist/cjs/security/events.js +84 -0
- package/dist/cjs/security/events.js.map +7 -0
- package/dist/cjs/types/index.d.ts +13 -11
- package/dist/cjs/types/index.d.ts.map +1 -1
- package/dist/cjs/types/index.js +3 -1
- package/dist/cjs/types/index.js.map +2 -2
- package/dist/cjs/types/metadata.d.ts +12 -8
- package/dist/cjs/types/metadata.d.ts.map +1 -1
- package/dist/cjs/types/metadata.js.map +1 -1
- package/dist/esm/box/index.d.ts +3 -3
- package/dist/esm/box/index.d.ts.map +1 -1
- package/dist/esm/box/index.js +1 -1
- package/dist/esm/box/index.js.map +1 -1
- package/dist/esm/check/harness.d.ts.map +1 -1
- package/dist/esm/check/harness.js +25 -0
- package/dist/esm/check/harness.js.map +1 -1
- package/dist/esm/drawing/output.d.ts +2 -1
- package/dist/esm/drawing/output.d.ts.map +1 -1
- package/dist/esm/drawing/output.js +9 -7
- package/dist/esm/drawing/output.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/label/index.d.ts +2 -2
- package/dist/esm/label/index.d.ts.map +1 -1
- package/dist/esm/label/index.js.map +1 -1
- package/dist/esm/line/index.d.ts +4 -4
- package/dist/esm/line/index.d.ts.map +1 -1
- package/dist/esm/line/index.js +3 -3
- package/dist/esm/line/index.js.map +1 -1
- package/dist/esm/polyline/index.d.ts +2 -2
- package/dist/esm/polyline/index.d.ts.map +1 -1
- package/dist/esm/polyline/index.js +1 -1
- package/dist/esm/polyline/index.js.map +1 -1
- package/dist/esm/script/constants.d.ts +6 -1
- package/dist/esm/script/constants.d.ts.map +1 -1
- package/dist/esm/script/constants.js +6 -1
- package/dist/esm/script/constants.js.map +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/index.d.ts +255 -28
- package/dist/esm/script/index.d.ts.map +1 -1
- package/dist/esm/script/index.js +370 -38
- package/dist/esm/script/index.js.map +1 -1
- package/dist/esm/security/events.d.ts +16 -0
- package/dist/esm/security/events.d.ts.map +1 -0
- package/dist/esm/security/events.js +78 -0
- package/dist/esm/security/events.js.map +1 -0
- package/dist/esm/types/index.d.ts +13 -11
- package/dist/esm/types/index.d.ts.map +1 -1
- package/dist/esm/types/index.js +3 -1
- package/dist/esm/types/index.js.map +1 -1
- package/dist/esm/types/metadata.d.ts +12 -8
- package/dist/esm/types/metadata.d.ts.map +1 -1
- package/package.json +1 -1
- package/skills/oakscript/reference/pine-differences.md +2 -0
- package/skills/oakscript/reference/plotting.md +24 -1
- package/skills/oakscript/reference/timeframes-symbols.md +27 -0
- package/src/box/index.ts +4 -4
- package/src/check/harness.ts +27 -0
- package/src/drawing/output.ts +12 -8
- package/src/index.ts +1 -1
- package/src/label/index.ts +3 -3
- package/src/line/index.ts +6 -6
- package/src/polyline/index.ts +2 -2
- package/src/script/constants.ts +6 -1
- package/src/script/globals.ts +3 -0
- package/src/script/index.ts +580 -50
- package/src/security/events.ts +85 -0
- package/src/types/index.ts +13 -11
- package/src/types/metadata.ts +12 -8
package/src/script/index.ts
CHANGED
|
@@ -138,6 +138,7 @@ import { TradingCalendar, type SessionSpec } from '../session/calendar.js';
|
|
|
138
138
|
import { SessionBars, sessionFlags, strayPeriods, type SessionFlags } from '../session/bars.js';
|
|
139
139
|
import { afterCompletion, heikinAshi, mapToChart, periodsOf, resample } from '../security/resample.js';
|
|
140
140
|
import { securityLowerTf, securityOther, type OtherSymbolChart } from '../security/other.js';
|
|
141
|
+
import { eventsOnBars } from '../security/events.js';
|
|
141
142
|
import { position } from '../types/index.js';
|
|
142
143
|
import type { Box, ChartPoint, Label, Line, Linefill, Polyline, Table } from '../types/index.js';
|
|
143
144
|
import {
|
|
@@ -199,6 +200,9 @@ export interface ScriptRunResult {
|
|
|
199
200
|
/** The script called alert() during the run (PineScript `hasAlertFunction` is known at compile time: a host that
|
|
200
201
|
* needs it before any bar runs reads the source). */
|
|
201
202
|
hasAlertFunction: boolean;
|
|
203
|
+
/** The script read `chart.left_visible_bar_time` or `chart.right_visible_bar_time`: it has to be calculated again when
|
|
204
|
+
* the visible range of the chart changes. */
|
|
205
|
+
usesVisibleRange: boolean;
|
|
202
206
|
}
|
|
203
207
|
|
|
204
208
|
export interface AlertConditionConfig {
|
|
@@ -277,6 +281,7 @@ interface Collector {
|
|
|
277
281
|
/** log.*() messages of the run. */
|
|
278
282
|
logs: LogEntry[];
|
|
279
283
|
hasAlertFunction: boolean;
|
|
284
|
+
usesVisibleRange: boolean;
|
|
280
285
|
strategy?: StrategyRun;
|
|
281
286
|
}
|
|
282
287
|
|
|
@@ -336,6 +341,7 @@ function freshCollector(inputValues: Record<string, unknown>): Collector {
|
|
|
336
341
|
alertCalls: [],
|
|
337
342
|
logs: [],
|
|
338
343
|
hasAlertFunction: false,
|
|
344
|
+
usesVisibleRange: false,
|
|
339
345
|
};
|
|
340
346
|
}
|
|
341
347
|
|
|
@@ -500,7 +506,14 @@ function runBody(
|
|
|
500
506
|
mathCore.resetRandom();
|
|
501
507
|
missingSymbols = [];
|
|
502
508
|
try {
|
|
503
|
-
|
|
509
|
+
try {
|
|
510
|
+
body();
|
|
511
|
+
} catch (err) {
|
|
512
|
+
// An expression of request.security runs on no bar and without the symbol's properties while its bars are not
|
|
513
|
+
// given (syminfo.sector there throws): the run waits for the data, not on the error.
|
|
514
|
+
if (missingSymbols.length && !(err instanceof MissingSymbolDataError)) throw new MissingSymbolDataError(missingSymbols);
|
|
515
|
+
throw err;
|
|
516
|
+
}
|
|
504
517
|
if (missingSymbols.length) throw new MissingSymbolDataError(missingSymbols);
|
|
505
518
|
// the outputs read the drawings: not a drawing of the script
|
|
506
519
|
if (inc) incremental.bodyDone();
|
|
@@ -545,6 +558,7 @@ function runBody(
|
|
|
545
558
|
logs: c.logs.length ? [...c.logs].sort((x, y) => x.bar - y.bar).slice(-MAX_LOG_ENTRIES) : undefined,
|
|
546
559
|
},
|
|
547
560
|
hasAlertFunction: c.hasAlertFunction,
|
|
561
|
+
usesVisibleRange: c.usesVisibleRange,
|
|
548
562
|
};
|
|
549
563
|
} finally {
|
|
550
564
|
ctx = null;
|
|
@@ -823,10 +837,13 @@ export interface ScriptRun {
|
|
|
823
837
|
/** Chart context fields that only change the last bar (barstate of the forming bar). */
|
|
824
838
|
const LAST_BAR_FIELDS = new Set(['lastBarConfirmed', 'lastBarNew', 'realtime', 'now']);
|
|
825
839
|
|
|
826
|
-
|
|
840
|
+
/** The visible range of the chart: part of the chart only for a script that reads it. */
|
|
841
|
+
const VISIBLE_RANGE_FIELDS = new Set(['leftVisibleBarTime', 'rightVisibleBarTime']);
|
|
842
|
+
|
|
843
|
+
function sameChart(a: ChartContext, b: ChartContext, visibleRange = true): boolean {
|
|
827
844
|
const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
|
|
828
845
|
for (const k of keys) {
|
|
829
|
-
if (LAST_BAR_FIELDS.has(k)) continue;
|
|
846
|
+
if (LAST_BAR_FIELDS.has(k) || (!visibleRange && VISIBLE_RANGE_FIELDS.has(k))) continue;
|
|
830
847
|
if (!Object.is((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) return false;
|
|
831
848
|
}
|
|
832
849
|
return true;
|
|
@@ -917,6 +934,8 @@ export function createScriptRun(
|
|
|
917
934
|
let previousChart: ChartContext = chart;
|
|
918
935
|
let reason: string | null = null;
|
|
919
936
|
let verifyLeft = options.verify ?? 2;
|
|
937
|
+
/** A bar calculated so far read the visible range. */
|
|
938
|
+
let rangeRead = false;
|
|
920
939
|
/** The log messages of the last update: a resumed update keeps those of the bars it does not calculate again. */
|
|
921
940
|
let lastLogs: LogEntry[] | undefined;
|
|
922
941
|
|
|
@@ -941,7 +960,7 @@ export function createScriptRun(
|
|
|
941
960
|
const last = previous;
|
|
942
961
|
const m = memory;
|
|
943
962
|
const resumable =
|
|
944
|
-
!reason && m !== null && last !== null && last.n >= 1 && b.length >= last.n && sameChart(previousChart, c) &&
|
|
963
|
+
!reason && m !== null && last !== null && last.n >= 1 && b.length >= last.n && sameChart(previousChart, c, rangeRead) &&
|
|
945
964
|
sameBars(last, b, last.n - 1);
|
|
946
965
|
previousChart = c;
|
|
947
966
|
let out: ScriptRunUpdate;
|
|
@@ -954,6 +973,7 @@ export function createScriptRun(
|
|
|
954
973
|
try {
|
|
955
974
|
result = runBody(body, b, inputs, c, options, inc);
|
|
956
975
|
result.result.logs = resumedLogs(lastLogs, result.result.logs, from);
|
|
976
|
+
result.usesVisibleRange ||= rangeRead;
|
|
957
977
|
} catch (err) {
|
|
958
978
|
// the memory is changed in place by a resumed run: an error leaves it unusable
|
|
959
979
|
memory = null;
|
|
@@ -964,6 +984,7 @@ export function createScriptRun(
|
|
|
964
984
|
if (result && verifyLeft > 0) {
|
|
965
985
|
verifyLeft--;
|
|
966
986
|
const check = runBody(body, b, inputs, c, options, null);
|
|
987
|
+
check.usesVisibleRange = result.usesVisibleRange;
|
|
967
988
|
if (!sameResult(result, check)) {
|
|
968
989
|
reason = 'a resumed update differs from a full run (state kept outside persist()?)';
|
|
969
990
|
result = check;
|
|
@@ -979,6 +1000,7 @@ export function createScriptRun(
|
|
|
979
1000
|
}
|
|
980
1001
|
previous = out.incremental && last ? copyBars(b, last, last.n - 1) : copyBars(b);
|
|
981
1002
|
lastLogs = out.result.logs;
|
|
1003
|
+
rangeRead = out.usesVisibleRange;
|
|
982
1004
|
return out;
|
|
983
1005
|
},
|
|
984
1006
|
};
|
|
@@ -1722,12 +1744,13 @@ export function fixnan(source: Series | Array<string | undefined>): Series | Arr
|
|
|
1722
1744
|
}
|
|
1723
1745
|
|
|
1724
1746
|
/** PineScript `na(x)`. On a Series: a Series of 1 / 0, 1 where the value is na (NaN or +/-Infinity, #187). On a
|
|
1725
|
-
* single value (a number of a bar loop, a colour, a drawing): true when it is na.
|
|
1747
|
+
* single value (a number of a bar loop, a colour, a drawing): true when it is na. An empty text is na, as in
|
|
1748
|
+
* PineScript (`na("")`, `na(syminfo.basecurrency)` of a stock). */
|
|
1726
1749
|
export function na(x: Series): Series;
|
|
1727
1750
|
export function na(x: unknown): boolean;
|
|
1728
1751
|
export function na(x: unknown): Series | boolean {
|
|
1729
1752
|
if (x instanceof Series) return Series.fromArray(ctxBars, x.toArray().map((v) => (isNA(v) ? 1 : 0)));
|
|
1730
|
-
return isNA(x);
|
|
1753
|
+
return x === '' || isNA(x);
|
|
1731
1754
|
}
|
|
1732
1755
|
|
|
1733
1756
|
/** PineScript `nz(source, replacement)`; replacement defaults to 0. On a Series: each na value (NaN or +/-Infinity)
|
|
@@ -3058,6 +3081,9 @@ export const strategy = Object.defineProperties(
|
|
|
3058
3081
|
variableGetters
|
|
3059
3082
|
) as StrategyApi;
|
|
3060
3083
|
|
|
3084
|
+
/** Types of chart PineScript tells apart (`chart.is_*`); every other type is 'standard'. */
|
|
3085
|
+
export type ChartType = 'standard' | 'heikinashi' | 'renko' | 'kagi' | 'linebreak' | 'pnf' | 'range';
|
|
3086
|
+
|
|
3061
3087
|
// ── Chart context (issue #100) ───────────────────────────────────────────────
|
|
3062
3088
|
|
|
3063
3089
|
/**
|
|
@@ -3105,17 +3131,67 @@ export interface ChartContext {
|
|
|
3105
3131
|
currency?: string;
|
|
3106
3132
|
/**
|
|
3107
3133
|
* Base currency of the symbol (PineScript `syminfo.basecurrency`): "BTC" for BITSTAMP:BTCUSD, BINANCE:BTCUSDT.P and
|
|
3108
|
-
* CME:BTC1!, "EUR" for FX:EURUSD, "" for a stock, an index or CME_MINI:ES1! (#180)
|
|
3134
|
+
* CME:BTC1!, "EUR" for FX:EURUSD, "" for a stock, an index or CME_MINI:ES1! (#180).
|
|
3135
|
+
*
|
|
3136
|
+
* The symbol fields below, like this one: a value; null when the symbol has none (PineScript gives na: "" for a
|
|
3137
|
+
* text, which `na()` takes as na, NaN for a number); left out when the host does not know it (reading it throws).
|
|
3138
|
+
*/
|
|
3139
|
+
basecurrency?: string | null;
|
|
3140
|
+
/**
|
|
3141
|
+
* Root of the symbol (PineScript `syminfo.root`): "BTC" for CME:BTC1!, "ES" for CME_MINI:ES1!, "AAPL" for
|
|
3142
|
+
* NASDAQ:AAPL (#180). Default: the ticker, without the "1!" of a continuous future or the month code and year of a
|
|
3143
|
+
* contract ("ESZ2026" of a `symbolType` "futures").
|
|
3109
3144
|
*/
|
|
3110
|
-
|
|
3111
|
-
/** Root of the symbol (PineScript `syminfo.root`): "BTC" for CME:BTC1!, "ES" for CME_MINI:ES1!, "AAPL" for NASDAQ:AAPL (#180) */
|
|
3112
|
-
root?: string;
|
|
3145
|
+
root?: string | null;
|
|
3113
3146
|
/** Description of the symbol (PineScript `syminfo.description`): "Apple Inc." for NASDAQ:AAPL, "Bitcoin / U.S. dollar" for BITSTAMP:BTCUSD (#184) */
|
|
3114
|
-
description?: string;
|
|
3147
|
+
description?: string | null;
|
|
3148
|
+
/** Prefix of the ticker id (PineScript `syminfo.prefix`), default: the part of `tickerid` before ":" */
|
|
3149
|
+
prefix?: string | null;
|
|
3150
|
+
/** Ticker without its prefix (PineScript `syminfo.ticker`), default: the part of `tickerid` after ":" */
|
|
3151
|
+
ticker?: string;
|
|
3152
|
+
/** The chart's own symbol (PineScript `syminfo.main_tickerid`, the same inside `request.security`); default `tickerid` */
|
|
3153
|
+
mainTickerid?: string;
|
|
3154
|
+
/** Two-letter code of the country the symbol trades in (PineScript `syminfo.country`): "US", "IN" */
|
|
3155
|
+
country?: string | null;
|
|
3156
|
+
/** Contract a continuous future stands for (PineScript `syminfo.current_contract`): "ESZ2026" for CME_MINI:ES1! */
|
|
3157
|
+
currentContract?: string | null;
|
|
3158
|
+
/** Last trading day of a future's contract, in ms (PineScript `syminfo.expiration_date`) */
|
|
3159
|
+
expirationDate?: number | null;
|
|
3160
|
+
/** PineScript `syminfo.sector` and `syminfo.industry` of a company */
|
|
3161
|
+
sector?: string | null;
|
|
3162
|
+
industry?: string | null;
|
|
3163
|
+
/** PineScript `syminfo.isin`: "US0378331005" for NASDAQ:AAPL */
|
|
3164
|
+
isin?: string | null;
|
|
3165
|
+
/** Unit of the volume (PineScript `syminfo.volumetype`): "base" (crypto: in the base currency), "quote", "tick", "n/a" */
|
|
3166
|
+
volumetype?: string | null;
|
|
3167
|
+
/** PineScript `syminfo.employees`, `syminfo.shareholders`, `syminfo.shares_outstanding_total` / `_float` */
|
|
3168
|
+
employees?: number | null;
|
|
3169
|
+
shareholders?: number | null;
|
|
3170
|
+
sharesOutstandingTotal?: number | null;
|
|
3171
|
+
sharesOutstandingFloat?: number | null;
|
|
3172
|
+
/** Analysts' ratings (PineScript `syminfo.recommendations_*`; `date` in ms) */
|
|
3173
|
+
recommendations?: SymbolRecommendations | null;
|
|
3174
|
+
/** Analysts' price targets (PineScript `syminfo.target_price_*`; `date` in ms) */
|
|
3175
|
+
targetPrice?: SymbolTargetPrice | null;
|
|
3176
|
+
/**
|
|
3177
|
+
* Dividends, splits and earnings of a symbol (PineScript `request.dividends`, `request.splits`, `request.earnings`,
|
|
3178
|
+
* `dividends.future_*`, `earnings.future_*`). Return undefined when they are not loaded: the run then ends with a
|
|
3179
|
+
* {@link MissingSymbolDataError} whose request has `events: true`. Return {} for a symbol without any.
|
|
3180
|
+
*/
|
|
3181
|
+
events?: (symbol: string) => SymbolEvents | undefined;
|
|
3115
3182
|
/** Chart foreground colour (PineScript `chart.fg_color`), e.g. "#DBDBDB" on a dark chart */
|
|
3116
3183
|
foregroundColor?: string;
|
|
3117
3184
|
/** Chart background colour (PineScript `chart.bg_color`), e.g. "#0F0F0F" on a dark chart */
|
|
3118
3185
|
backgroundColor?: string;
|
|
3186
|
+
/**
|
|
3187
|
+
* Times (ms) of the first and the last bar in view (PineScript `chart.left_visible_bar_time` and
|
|
3188
|
+
* `chart.right_visible_bar_time`); default: the first and the last bar. A script that reads them
|
|
3189
|
+
* ({@link ScriptRunResult.usesVisibleRange}) has to be calculated again when they change.
|
|
3190
|
+
*/
|
|
3191
|
+
leftVisibleBarTime?: number;
|
|
3192
|
+
rightVisibleBarTime?: number;
|
|
3193
|
+
/** Type of the chart (PineScript `chart.is_standard`, `chart.is_heikinashi`...); default 'standard' */
|
|
3194
|
+
chartType?: ChartType;
|
|
3119
3195
|
/** Current time in ms (PineScript `timenow`); default: the clock of the computer at the start of the run */
|
|
3120
3196
|
now?: number;
|
|
3121
3197
|
/**
|
|
@@ -3162,12 +3238,108 @@ export type SymbolInfo = Pick<
|
|
|
3162
3238
|
| 'basecurrency'
|
|
3163
3239
|
| 'root'
|
|
3164
3240
|
| 'description'
|
|
3241
|
+
| 'prefix'
|
|
3242
|
+
| 'ticker'
|
|
3243
|
+
| 'country'
|
|
3244
|
+
| 'currentContract'
|
|
3245
|
+
| 'expirationDate'
|
|
3246
|
+
| 'sector'
|
|
3247
|
+
| 'industry'
|
|
3248
|
+
| 'isin'
|
|
3249
|
+
| 'volumetype'
|
|
3250
|
+
| 'employees'
|
|
3251
|
+
| 'shareholders'
|
|
3252
|
+
| 'sharesOutstandingTotal'
|
|
3253
|
+
| 'sharesOutstandingFloat'
|
|
3254
|
+
| 'recommendations'
|
|
3255
|
+
| 'targetPrice'
|
|
3165
3256
|
>;
|
|
3166
3257
|
|
|
3167
|
-
/**
|
|
3258
|
+
/** The symbol fields a {@link SymbolInfo} gives to `syminfo.*` inside `request.security`. */
|
|
3259
|
+
const SYMBOL_INFO_KEYS = [
|
|
3260
|
+
'timezone', 'session', 'regularSession', 'mintick', 'minmove', 'pricescale', 'pointvalue', 'mincontract', 'symbolType',
|
|
3261
|
+
'currency', 'basecurrency', 'root', 'description', 'prefix', 'ticker', 'country', 'currentContract', 'expirationDate',
|
|
3262
|
+
'sector', 'industry', 'isin', 'volumetype', 'employees', 'shareholders', 'sharesOutstandingTotal',
|
|
3263
|
+
'sharesOutstandingFloat', 'recommendations', 'targetPrice',
|
|
3264
|
+
] as const satisfies readonly (keyof SymbolInfo)[];
|
|
3265
|
+
|
|
3266
|
+
/** Analysts' ratings of a symbol: counts of each rating, and the date of the count (ms). */
|
|
3267
|
+
export interface SymbolRecommendations {
|
|
3268
|
+
buy: number;
|
|
3269
|
+
buy_strong: number;
|
|
3270
|
+
hold: number;
|
|
3271
|
+
sell: number;
|
|
3272
|
+
sell_strong: number;
|
|
3273
|
+
total: number;
|
|
3274
|
+
date: number;
|
|
3275
|
+
}
|
|
3276
|
+
|
|
3277
|
+
/** Analysts' price targets of a symbol, their number and the date of the figures (ms). */
|
|
3278
|
+
export interface SymbolTargetPrice {
|
|
3279
|
+
average: number;
|
|
3280
|
+
high: number;
|
|
3281
|
+
low: number;
|
|
3282
|
+
median: number;
|
|
3283
|
+
estimates: number;
|
|
3284
|
+
date: number;
|
|
3285
|
+
}
|
|
3286
|
+
|
|
3287
|
+
/**
|
|
3288
|
+
* A dividend: `time` the ex-date (ms; 00:00 UTC of the day, as PineScript's dividends are stamped), the amount per
|
|
3289
|
+
* share as declared (not adjusted for later splits), net and gross of withholding tax (gross defaults to net).
|
|
3290
|
+
*/
|
|
3291
|
+
export interface DividendEvent {
|
|
3292
|
+
time: number;
|
|
3293
|
+
net: number;
|
|
3294
|
+
gross?: number;
|
|
3295
|
+
/** Payment date (ms) */
|
|
3296
|
+
payDate?: number | null;
|
|
3297
|
+
}
|
|
3298
|
+
|
|
3299
|
+
/** A split from `denominator` shares to `numerator` (4 and 1 for a 4-for-1 split); `time` its date (ms, 00:00 UTC). */
|
|
3300
|
+
export interface SplitEvent {
|
|
3301
|
+
time: number;
|
|
3302
|
+
numerator: number;
|
|
3303
|
+
denominator: number;
|
|
3304
|
+
}
|
|
3305
|
+
|
|
3306
|
+
/**
|
|
3307
|
+
* An earnings release: `time` when it was published (ms; a release after the close is after the session's close). The
|
|
3308
|
+
* values per share are adjusted for later splits, as PineScript gives them. A value the host does not have is left
|
|
3309
|
+
* out; a script that asks for it then stops with an error.
|
|
3310
|
+
*/
|
|
3311
|
+
export interface EarningsEvent {
|
|
3312
|
+
time: number;
|
|
3313
|
+
/** Reported earnings per share (`earnings.actual`), the analysts' estimate (`earnings.estimate`), standardized
|
|
3314
|
+
* earnings per share (`earnings.standardized`) */
|
|
3315
|
+
actual?: number | null;
|
|
3316
|
+
estimate?: number | null;
|
|
3317
|
+
standardized?: number | null;
|
|
3318
|
+
/** Estimated revenue (`earnings.future_revenue`) and the end of the fiscal period (ms) */
|
|
3319
|
+
revenueEstimate?: number | null;
|
|
3320
|
+
periodEnd?: number | null;
|
|
3321
|
+
}
|
|
3322
|
+
|
|
3323
|
+
/** Events of a symbol, oldest first. */
|
|
3324
|
+
export interface SymbolEvents {
|
|
3325
|
+
dividends?: DividendEvent[];
|
|
3326
|
+
splits?: SplitEvent[];
|
|
3327
|
+
earnings?: EarningsEvent[];
|
|
3328
|
+
/**
|
|
3329
|
+
* The lists hold the announced events still to come (`dividends.future_*`, `earnings.future_*` read them): without
|
|
3330
|
+
* it the future values are not known and reading them throws.
|
|
3331
|
+
*/
|
|
3332
|
+
future?: { dividends?: boolean; earnings?: boolean };
|
|
3333
|
+
}
|
|
3334
|
+
|
|
3335
|
+
/**
|
|
3336
|
+
* A request of `request.security` for another symbol whose bars the host has not given, or (`events`) of
|
|
3337
|
+
* `request.dividends` / `request.splits` / `request.earnings` for a symbol whose events it has not given.
|
|
3338
|
+
*/
|
|
3168
3339
|
export interface SymbolDataRequest {
|
|
3169
3340
|
symbol: string;
|
|
3170
3341
|
timeframe: string;
|
|
3342
|
+
events?: boolean;
|
|
3171
3343
|
}
|
|
3172
3344
|
|
|
3173
3345
|
/**
|
|
@@ -3176,9 +3348,13 @@ export interface SymbolDataRequest {
|
|
|
3176
3348
|
*/
|
|
3177
3349
|
export class MissingSymbolDataError extends Error {
|
|
3178
3350
|
constructor(readonly requests: SymbolDataRequest[]) {
|
|
3351
|
+
const bars = requests.filter((r) => !r.events);
|
|
3352
|
+
const events = requests.filter((r) => r.events);
|
|
3179
3353
|
super(
|
|
3180
|
-
|
|
3181
|
-
'pass them with ChartContext.bars
|
|
3354
|
+
[
|
|
3355
|
+
bars.length ? `request.security needs the bars of ${bars.map((r) => `${r.symbol} (${r.timeframe})`).join(', ')}: pass them with ChartContext.bars.` : '',
|
|
3356
|
+
events.length ? `The script needs the events of ${events.map((r) => r.symbol).join(', ')}: pass them with ChartContext.events.` : '',
|
|
3357
|
+
].filter(Boolean).join(' ')
|
|
3182
3358
|
);
|
|
3183
3359
|
this.name = 'MissingSymbolDataError';
|
|
3184
3360
|
}
|
|
@@ -3267,9 +3443,23 @@ function symbolProperty(key: 'mintick' | 'pointvalue' | 'mincontract'): number {
|
|
|
3267
3443
|
return value;
|
|
3268
3444
|
}
|
|
3269
3445
|
|
|
3270
|
-
/** A text value of the chart or the symbol that the host passes in the chart context. */
|
|
3446
|
+
/** A text value of the chart or the symbol that the host passes in the chart context; null (none) is "". */
|
|
3271
3447
|
function chartText(
|
|
3272
|
-
key:
|
|
3448
|
+
key:
|
|
3449
|
+
| 'symbolType'
|
|
3450
|
+
| 'currency'
|
|
3451
|
+
| 'basecurrency'
|
|
3452
|
+
| 'root'
|
|
3453
|
+
| 'description'
|
|
3454
|
+
| 'foregroundColor'
|
|
3455
|
+
| 'backgroundColor'
|
|
3456
|
+
| 'prefix'
|
|
3457
|
+
| 'country'
|
|
3458
|
+
| 'currentContract'
|
|
3459
|
+
| 'sector'
|
|
3460
|
+
| 'industry'
|
|
3461
|
+
| 'isin'
|
|
3462
|
+
| 'volumetype',
|
|
3273
3463
|
name: string
|
|
3274
3464
|
): string {
|
|
3275
3465
|
collector();
|
|
@@ -3277,7 +3467,74 @@ function chartText(
|
|
|
3277
3467
|
if (value === undefined) {
|
|
3278
3468
|
throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);
|
|
3279
3469
|
}
|
|
3280
|
-
|
|
3470
|
+
// PineScript's na text is "" (`na("")` is true)
|
|
3471
|
+
return value ?? '';
|
|
3472
|
+
}
|
|
3473
|
+
|
|
3474
|
+
/** A number of the symbol that the host passes in the chart context; null (none) is na. */
|
|
3475
|
+
function symbolNumber(
|
|
3476
|
+
key: 'expirationDate' | 'employees' | 'shareholders' | 'sharesOutstandingTotal' | 'sharesOutstandingFloat',
|
|
3477
|
+
name: string
|
|
3478
|
+
): number {
|
|
3479
|
+
collector();
|
|
3480
|
+
const value = chartCtx[key];
|
|
3481
|
+
if (value === undefined) {
|
|
3482
|
+
throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);
|
|
3483
|
+
}
|
|
3484
|
+
return value ?? NaN;
|
|
3485
|
+
}
|
|
3486
|
+
|
|
3487
|
+
/** A value of the analysts' figures of the symbol (`recommendations`, `targetPrice`); null (none) is na. */
|
|
3488
|
+
function analystNumber<K extends 'recommendations' | 'targetPrice'>(
|
|
3489
|
+
key: K,
|
|
3490
|
+
field: keyof NonNullable<ChartContext[K]>,
|
|
3491
|
+
name: string
|
|
3492
|
+
): number {
|
|
3493
|
+
collector();
|
|
3494
|
+
const group = chartCtx[key];
|
|
3495
|
+
if (group === undefined) {
|
|
3496
|
+
throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);
|
|
3497
|
+
}
|
|
3498
|
+
return group === null ? NaN : ((group as unknown as Record<string, number>)[field as string] ?? NaN);
|
|
3499
|
+
}
|
|
3500
|
+
|
|
3501
|
+
/** The ticker id of the chart (or of the symbol of `request.security`); throws when not known. */
|
|
3502
|
+
function chartTickerid(): string {
|
|
3503
|
+
collector();
|
|
3504
|
+
if (!chartCtx.tickerid) {
|
|
3505
|
+
throw new Error('The chart symbol is not known: pass it as executeScript(body, bars, inputs, { tickerid }).');
|
|
3506
|
+
}
|
|
3507
|
+
return chartCtx.tickerid;
|
|
3508
|
+
}
|
|
3509
|
+
|
|
3510
|
+
/** A ticker id cut at its prefix: ["NASDAQ", "AAPL"], ["", "AAPL"] without one. */
|
|
3511
|
+
function splitTickerid(tickerid: string): [string, string] {
|
|
3512
|
+
const at = tickerid.indexOf(':');
|
|
3513
|
+
return at < 0 ? ['', tickerid] : [tickerid.slice(0, at), tickerid.slice(at + 1)];
|
|
3514
|
+
}
|
|
3515
|
+
|
|
3516
|
+
/** Month codes of futures contracts (F = January ... Z = December). */
|
|
3517
|
+
const CONTRACT_SUFFIX = /^(.+?)[FGHJKMNQUVXZ](\d{4}|\d{2})$/;
|
|
3518
|
+
|
|
3519
|
+
/** Root of a ticker: without the "1!" of a continuous future, or the month code and year of a future's contract. */
|
|
3520
|
+
function tickerRoot(ticker: string, symbolType: string | undefined): string {
|
|
3521
|
+
const continuous = /^(.+?)\d+!$/.exec(ticker);
|
|
3522
|
+
if (continuous) return continuous[1]!;
|
|
3523
|
+
const contract = symbolType === 'futures' ? CONTRACT_SUFFIX.exec(ticker) : null;
|
|
3524
|
+
return contract ? contract[1]! : ticker;
|
|
3525
|
+
}
|
|
3526
|
+
|
|
3527
|
+
/** A visible range value: the chart context's, else the time of bar `index` (NaN without bars). */
|
|
3528
|
+
function visibleBarTime(value: number | undefined, index: number): number {
|
|
3529
|
+
collector().usesVisibleRange = true;
|
|
3530
|
+
if (value !== undefined) return value;
|
|
3531
|
+
const bar = ctxBars.bars[index];
|
|
3532
|
+
return bar ? barTime(bar) : NaN;
|
|
3533
|
+
}
|
|
3534
|
+
|
|
3535
|
+
function chartTypeIs(type: ChartType): boolean {
|
|
3536
|
+
collector();
|
|
3537
|
+
return (chartCtx.chartType ?? 'standard') === type;
|
|
3281
3538
|
}
|
|
3282
3539
|
|
|
3283
3540
|
/** `[minmove, pricescale]` of the chart symbol: from the chart context, else from its mintick. */
|
|
@@ -3290,9 +3547,8 @@ function symbolScale(): [number, number] {
|
|
|
3290
3547
|
}
|
|
3291
3548
|
|
|
3292
3549
|
/**
|
|
3293
|
-
* PineScript `syminfo
|
|
3294
|
-
*
|
|
3295
|
-
* `syminfo.currency`, `syminfo.basecurrency`, `syminfo.root` and `syminfo.description`, from the chart context.
|
|
3550
|
+
* PineScript `syminfo.*`, from the chart context (inside `request.security`, the requested symbol's). A field the
|
|
3551
|
+
* symbol has none of is na ("" for a text); a field the host did not give throws.
|
|
3296
3552
|
*/
|
|
3297
3553
|
export const syminfo = {
|
|
3298
3554
|
get mintick(): number {
|
|
@@ -3314,11 +3570,19 @@ export const syminfo = {
|
|
|
3314
3570
|
return exchangeTimezone();
|
|
3315
3571
|
},
|
|
3316
3572
|
get tickerid(): string {
|
|
3317
|
-
|
|
3318
|
-
|
|
3319
|
-
|
|
3320
|
-
|
|
3321
|
-
return chartCtx.
|
|
3573
|
+
return chartTickerid();
|
|
3574
|
+
},
|
|
3575
|
+
get main_tickerid(): string {
|
|
3576
|
+
const id = chartTickerid();
|
|
3577
|
+
return chartCtx.mainTickerid ?? id;
|
|
3578
|
+
},
|
|
3579
|
+
get ticker(): string {
|
|
3580
|
+
const id = chartTickerid();
|
|
3581
|
+
return chartCtx.ticker ?? splitTickerid(id)[1];
|
|
3582
|
+
},
|
|
3583
|
+
get prefix(): string {
|
|
3584
|
+
const id = chartTickerid();
|
|
3585
|
+
return chartCtx.prefix === undefined ? splitTickerid(id)[0] : (chartCtx.prefix ?? '');
|
|
3322
3586
|
},
|
|
3323
3587
|
get session(): string {
|
|
3324
3588
|
collector();
|
|
@@ -3334,11 +3598,84 @@ export const syminfo = {
|
|
|
3334
3598
|
return chartText('basecurrency', 'syminfo.basecurrency');
|
|
3335
3599
|
},
|
|
3336
3600
|
get root(): string {
|
|
3337
|
-
return chartText('root', 'syminfo.root');
|
|
3601
|
+
if (chartCtx.root !== undefined) return chartText('root', 'syminfo.root');
|
|
3602
|
+
return tickerRoot(syminfo.ticker, chartCtx.symbolType);
|
|
3338
3603
|
},
|
|
3339
3604
|
get description(): string {
|
|
3340
3605
|
return chartText('description', 'syminfo.description');
|
|
3341
3606
|
},
|
|
3607
|
+
get country(): string {
|
|
3608
|
+
return chartText('country', 'syminfo.country');
|
|
3609
|
+
},
|
|
3610
|
+
get current_contract(): string {
|
|
3611
|
+
return chartText('currentContract', 'syminfo.current_contract');
|
|
3612
|
+
},
|
|
3613
|
+
get expiration_date(): number {
|
|
3614
|
+
return symbolNumber('expirationDate', 'syminfo.expiration_date');
|
|
3615
|
+
},
|
|
3616
|
+
get sector(): string {
|
|
3617
|
+
return chartText('sector', 'syminfo.sector');
|
|
3618
|
+
},
|
|
3619
|
+
get industry(): string {
|
|
3620
|
+
return chartText('industry', 'syminfo.industry');
|
|
3621
|
+
},
|
|
3622
|
+
get isin(): string {
|
|
3623
|
+
return chartText('isin', 'syminfo.isin');
|
|
3624
|
+
},
|
|
3625
|
+
get volumetype(): string {
|
|
3626
|
+
return chartText('volumetype', 'syminfo.volumetype');
|
|
3627
|
+
},
|
|
3628
|
+
get employees(): number {
|
|
3629
|
+
return symbolNumber('employees', 'syminfo.employees');
|
|
3630
|
+
},
|
|
3631
|
+
get shareholders(): number {
|
|
3632
|
+
return symbolNumber('shareholders', 'syminfo.shareholders');
|
|
3633
|
+
},
|
|
3634
|
+
get shares_outstanding_total(): number {
|
|
3635
|
+
return symbolNumber('sharesOutstandingTotal', 'syminfo.shares_outstanding_total');
|
|
3636
|
+
},
|
|
3637
|
+
get shares_outstanding_float(): number {
|
|
3638
|
+
return symbolNumber('sharesOutstandingFloat', 'syminfo.shares_outstanding_float');
|
|
3639
|
+
},
|
|
3640
|
+
get recommendations_buy(): number {
|
|
3641
|
+
return analystNumber('recommendations', 'buy', 'syminfo.recommendations_buy');
|
|
3642
|
+
},
|
|
3643
|
+
get recommendations_buy_strong(): number {
|
|
3644
|
+
return analystNumber('recommendations', 'buy_strong', 'syminfo.recommendations_buy_strong');
|
|
3645
|
+
},
|
|
3646
|
+
get recommendations_hold(): number {
|
|
3647
|
+
return analystNumber('recommendations', 'hold', 'syminfo.recommendations_hold');
|
|
3648
|
+
},
|
|
3649
|
+
get recommendations_sell(): number {
|
|
3650
|
+
return analystNumber('recommendations', 'sell', 'syminfo.recommendations_sell');
|
|
3651
|
+
},
|
|
3652
|
+
get recommendations_sell_strong(): number {
|
|
3653
|
+
return analystNumber('recommendations', 'sell_strong', 'syminfo.recommendations_sell_strong');
|
|
3654
|
+
},
|
|
3655
|
+
get recommendations_total(): number {
|
|
3656
|
+
return analystNumber('recommendations', 'total', 'syminfo.recommendations_total');
|
|
3657
|
+
},
|
|
3658
|
+
get recommendations_date(): number {
|
|
3659
|
+
return analystNumber('recommendations', 'date', 'syminfo.recommendations_date');
|
|
3660
|
+
},
|
|
3661
|
+
get target_price_average(): number {
|
|
3662
|
+
return analystNumber('targetPrice', 'average', 'syminfo.target_price_average');
|
|
3663
|
+
},
|
|
3664
|
+
get target_price_high(): number {
|
|
3665
|
+
return analystNumber('targetPrice', 'high', 'syminfo.target_price_high');
|
|
3666
|
+
},
|
|
3667
|
+
get target_price_low(): number {
|
|
3668
|
+
return analystNumber('targetPrice', 'low', 'syminfo.target_price_low');
|
|
3669
|
+
},
|
|
3670
|
+
get target_price_median(): number {
|
|
3671
|
+
return analystNumber('targetPrice', 'median', 'syminfo.target_price_median');
|
|
3672
|
+
},
|
|
3673
|
+
get target_price_estimates(): number {
|
|
3674
|
+
return analystNumber('targetPrice', 'estimates', 'syminfo.target_price_estimates');
|
|
3675
|
+
},
|
|
3676
|
+
get target_price_date(): number {
|
|
3677
|
+
return analystNumber('targetPrice', 'date', 'syminfo.target_price_date');
|
|
3678
|
+
},
|
|
3342
3679
|
};
|
|
3343
3680
|
|
|
3344
3681
|
/** A calendar function: `(time, timezone?)` on a UNIX time or on a Series of times. */
|
|
@@ -3770,25 +4107,11 @@ function runExternal<T extends SecurityValue>(
|
|
|
3770
4107
|
let result: T;
|
|
3771
4108
|
let values: number[][];
|
|
3772
4109
|
ctxBars.setAll(bars);
|
|
3773
|
-
// the expression sees that symbol: its ticker, timeframe, calendar and properties
|
|
3774
|
-
|
|
3775
|
-
|
|
3776
|
-
|
|
3777
|
-
|
|
3778
|
-
timezone: info.timezone,
|
|
3779
|
-
session: info.session,
|
|
3780
|
-
regularSession: info.regularSession,
|
|
3781
|
-
mintick: info.mintick,
|
|
3782
|
-
minmove: info.minmove,
|
|
3783
|
-
pricescale: info.pricescale,
|
|
3784
|
-
pointvalue: info.pointvalue,
|
|
3785
|
-
mincontract: info.mincontract,
|
|
3786
|
-
symbolType: info.symbolType,
|
|
3787
|
-
currency: info.currency,
|
|
3788
|
-
basecurrency: info.basecurrency,
|
|
3789
|
-
root: info.root,
|
|
3790
|
-
description: info.description,
|
|
3791
|
-
};
|
|
4110
|
+
// the expression sees that symbol: its ticker, timeframe, calendar and properties (the chart's own symbol stays the
|
|
4111
|
+
// main one)
|
|
4112
|
+
const seen: ChartContext = { ...chartCtx, tickerid: symbol, timeframe: tf, mainTickerid: chartCtx.mainTickerid ?? chartCtx.tickerid };
|
|
4113
|
+
for (const key of SYMBOL_INFO_KEYS) (seen as Record<string, unknown>)[key] = info[key];
|
|
4114
|
+
chartCtx = seen;
|
|
3792
4115
|
try {
|
|
3793
4116
|
result = expression();
|
|
3794
4117
|
const parts = Array.isArray(result) ? result : [result];
|
|
@@ -3965,7 +4288,182 @@ function seedCall<T extends SecurityValue>(
|
|
|
3965
4288
|
return seed(a[0] as string, a[1] as string, a[2] as () => T, a[3] as boolean | undefined);
|
|
3966
4289
|
}
|
|
3967
4290
|
|
|
3968
|
-
|
|
4291
|
+
// ── request.dividends / request.splits / request.earnings (#211) ─────────────
|
|
4292
|
+
|
|
4293
|
+
/** The events of `ticker` ("" or the chart's: the chart symbol); {} while the host has not given them (the run ends with
|
|
4294
|
+
* a MissingSymbolDataError). */
|
|
4295
|
+
function symbolEvents(ticker: string): SymbolEvents {
|
|
4296
|
+
collector();
|
|
4297
|
+
const symbol = ticker === '' ? chartTickerid() : ticker;
|
|
4298
|
+
const events = chartCtx.events?.(symbol);
|
|
4299
|
+
if (events === undefined) {
|
|
4300
|
+
if (!missingSymbols.some((r) => r.events && r.symbol === symbol)) missingSymbols.push({ symbol, timeframe: '', events: true });
|
|
4301
|
+
return {};
|
|
4302
|
+
}
|
|
4303
|
+
return events;
|
|
4304
|
+
}
|
|
4305
|
+
|
|
4306
|
+
/** One value of each event; throws when no event has it (the host does not have it), na where one has none. */
|
|
4307
|
+
function eventField<E extends object>(list: E[], field: keyof E, name: string, ticker: string): number[] {
|
|
4308
|
+
if (list.length && list.every((e) => e[field] === undefined)) {
|
|
4309
|
+
throw new Error(`${name}: the ${String(field)} values of ${ticker || 'the chart symbol'} are not known.`);
|
|
4310
|
+
}
|
|
4311
|
+
return list.map((e) => {
|
|
4312
|
+
const v = e[field] as unknown;
|
|
4313
|
+
return typeof v === 'number' ? v : NaN;
|
|
4314
|
+
});
|
|
4315
|
+
}
|
|
4316
|
+
|
|
4317
|
+
/** A Series of event values on the chart bars, placed by PineScript's rules (see `security/events`). */
|
|
4318
|
+
function eventSeries(times: number[], values: number[], gaps: string | undefined, lookahead: string | undefined): Series {
|
|
4319
|
+
incremental.nonIncremental('request.dividends / splits / earnings');
|
|
4320
|
+
const opens = ctxBars.bars.map(barTime);
|
|
4321
|
+
const tf = chartTimeframe().period;
|
|
4322
|
+
const span = timeframeCore.info(tf).isticks ? 0 : timeframeCore.in_seconds(tf) * 1000;
|
|
4323
|
+
const { bars } = sessionBars();
|
|
4324
|
+
// a bar without a session period closes where the next one opens
|
|
4325
|
+
const closes = opens.map((t, i) => {
|
|
4326
|
+
const c = bars.closeOf(t, tf);
|
|
4327
|
+
return Number.isFinite(c) ? c : (opens[i + 1] ?? t + span);
|
|
4328
|
+
});
|
|
4329
|
+
const order = times.map((_, i) => i).sort((a, b) => times[a]! - times[b]!);
|
|
4330
|
+
const events = order.map((i) => ({ time: times[i]!, value: values[i]! }));
|
|
4331
|
+
return Series.fromArray(
|
|
4332
|
+
ctxBars,
|
|
4333
|
+
eventsOnBars(opens, closes, tf, events, { gaps: gaps === barmerge.gaps_on, lookahead: lookahead === barmerge.lookahead_on })
|
|
4334
|
+
);
|
|
4335
|
+
}
|
|
4336
|
+
|
|
4337
|
+
/** PineScript `dividends.*`: the fields of `request.dividends` and the next announced dividend of the chart symbol. */
|
|
4338
|
+
export const dividends = {
|
|
4339
|
+
net: 'net',
|
|
4340
|
+
gross: 'gross',
|
|
4341
|
+
/** Amount of the next dividend (net), na when none is announced */
|
|
4342
|
+
get future_amount(): number {
|
|
4343
|
+
return nextDividend()?.net ?? NaN;
|
|
4344
|
+
},
|
|
4345
|
+
/** Ex-date of the next dividend (ms) */
|
|
4346
|
+
get future_ex_date(): number {
|
|
4347
|
+
return nextDividend()?.time ?? NaN;
|
|
4348
|
+
},
|
|
4349
|
+
/** Payment date of the next dividend (ms) */
|
|
4350
|
+
get future_pay_date(): number {
|
|
4351
|
+
return nextDividend()?.payDate ?? NaN;
|
|
4352
|
+
},
|
|
4353
|
+
} as const;
|
|
4354
|
+
|
|
4355
|
+
/** PineScript `splits.*`: the fields of `request.splits`. */
|
|
4356
|
+
export const splits = { numerator: 'numerator', denominator: 'denominator' } as const;
|
|
4357
|
+
|
|
4358
|
+
/** PineScript `earnings.*`: the fields of `request.earnings` and the next earnings release of the chart symbol. */
|
|
4359
|
+
export const earnings = {
|
|
4360
|
+
actual: 'actual',
|
|
4361
|
+
estimate: 'estimate',
|
|
4362
|
+
standardized: 'standardized',
|
|
4363
|
+
/** Estimated earnings per share of the next release */
|
|
4364
|
+
get future_eps(): number {
|
|
4365
|
+
return nextEarnings()?.estimate ?? NaN;
|
|
4366
|
+
},
|
|
4367
|
+
/** Estimated revenue of the next release */
|
|
4368
|
+
get future_revenue(): number {
|
|
4369
|
+
return nextEarnings()?.revenueEstimate ?? NaN;
|
|
4370
|
+
},
|
|
4371
|
+
/** Time of the next release (ms) */
|
|
4372
|
+
get future_time(): number {
|
|
4373
|
+
return nextEarnings()?.time ?? NaN;
|
|
4374
|
+
},
|
|
4375
|
+
/** End of the fiscal period of the next release (ms) */
|
|
4376
|
+
get future_period_end_time(): number {
|
|
4377
|
+
return nextEarnings()?.periodEnd ?? NaN;
|
|
4378
|
+
},
|
|
4379
|
+
} as const;
|
|
4380
|
+
|
|
4381
|
+
/** The first event after the current time of the run in the chart symbol's list, when the host gives the announced ones. */
|
|
4382
|
+
function nextEvent<K extends 'dividends' | 'earnings'>(kind: K): NonNullable<SymbolEvents[K]>[number] | undefined {
|
|
4383
|
+
const events = symbolEvents('');
|
|
4384
|
+
if (!Object.keys(events).length) return undefined;
|
|
4385
|
+
if (!events.future?.[kind]) throw new Error(`${kind}.future_*: the announced ${kind} of ${chartTickerid()} are not known.`);
|
|
4386
|
+
return (events[kind] as Array<{ time: number }> | undefined)?.find((e) => e.time > runNow) as NonNullable<SymbolEvents[K]>[number] | undefined;
|
|
4387
|
+
}
|
|
4388
|
+
const nextDividend = (): DividendEvent | undefined => nextEvent('dividends');
|
|
4389
|
+
const nextEarnings = (): EarningsEvent | undefined => nextEvent('earnings');
|
|
4390
|
+
|
|
4391
|
+
const DIVIDENDS_PARAMETERS = ['ticker', 'field', 'gaps', 'lookahead', 'ignore_invalid_symbol', 'currency'] as const;
|
|
4392
|
+
const SPLITS_PARAMETERS = ['ticker', 'field', 'gaps', 'lookahead', 'ignore_invalid_symbol'] as const;
|
|
4393
|
+
|
|
4394
|
+
/** Named arguments of `request.dividends` / `request.earnings` (`request.splits` has no `currency`). */
|
|
4395
|
+
export interface EventRequestArgs {
|
|
4396
|
+
ticker?: string;
|
|
4397
|
+
field?: string;
|
|
4398
|
+
gaps?: string;
|
|
4399
|
+
lookahead?: string;
|
|
4400
|
+
ignore_invalid_symbol?: boolean;
|
|
4401
|
+
currency?: string;
|
|
4402
|
+
}
|
|
4403
|
+
|
|
4404
|
+
type EventRequestCall =
|
|
4405
|
+
| [ticker: string, field?: string, gaps?: string, lookahead?: string, ignore_invalid_symbol?: boolean, currency?: string]
|
|
4406
|
+
| [ticker: string, field: string, args: EventRequestArgs]
|
|
4407
|
+
| [ticker: string, args: EventRequestArgs]
|
|
4408
|
+
| [args: EventRequestArgs & { ticker: string }];
|
|
4409
|
+
|
|
4410
|
+
/**
|
|
4411
|
+
* PineScript `request.dividends(ticker, field, gaps, lookahead, ignore_invalid_symbol, currency)`: the dividend per
|
|
4412
|
+
* share (`dividends.net`, default, or `dividends.gross`) as declared, from the bar after its ex-date's day (see
|
|
4413
|
+
* `security/events`). na before the first dividend. The events come from `ChartContext.events`.
|
|
4414
|
+
*/
|
|
4415
|
+
function dividendsCall(...args: EventRequestCall): Series {
|
|
4416
|
+
const a = namedArguments('request.dividends', DIVIDENDS_PARAMETERS, args);
|
|
4417
|
+
unsupportedSecurityArgs('request.dividends', a[5], undefined);
|
|
4418
|
+
const ticker = (a[0] as string | undefined) ?? '';
|
|
4419
|
+
const field = (a[1] as string | undefined) ?? dividends.net;
|
|
4420
|
+
if (field !== dividends.net && field !== dividends.gross) throw new Error(`request.dividends(): unknown field "${field}": dividends.net or dividends.gross.`);
|
|
4421
|
+
const list = symbolEvents(ticker).dividends ?? [];
|
|
4422
|
+
const values = field === dividends.gross ? list.map((d) => d.gross ?? d.net) : eventField(list, 'net', 'request.dividends', ticker);
|
|
4423
|
+
return eventSeries(list.map((d) => d.time), values, a[2] as string | undefined, a[3] as string | undefined);
|
|
4424
|
+
}
|
|
4425
|
+
|
|
4426
|
+
/**
|
|
4427
|
+
* PineScript `request.splits(ticker, field, gaps, lookahead, ignore_invalid_symbol)`: the numerator
|
|
4428
|
+
* (`splits.numerator`) or the denominator (`splits.denominator`) of the last split, from the bar after its day.
|
|
4429
|
+
*/
|
|
4430
|
+
function splitsCall(...args: EventRequestCall): Series {
|
|
4431
|
+
const a = namedArguments('request.splits', SPLITS_PARAMETERS, args);
|
|
4432
|
+
const ticker = (a[0] as string | undefined) ?? '';
|
|
4433
|
+
const field = a[1] as string | undefined;
|
|
4434
|
+
if (field !== splits.numerator && field !== splits.denominator) {
|
|
4435
|
+
throw new Error('request.splits(): the field is splits.numerator or splits.denominator.');
|
|
4436
|
+
}
|
|
4437
|
+
const list = symbolEvents(ticker).splits ?? [];
|
|
4438
|
+
return eventSeries(list.map((s) => s.time), eventField(list, field, 'request.splits', ticker), a[2] as string | undefined, a[3] as string | undefined);
|
|
4439
|
+
}
|
|
4440
|
+
|
|
4441
|
+
/**
|
|
4442
|
+
* PineScript `request.earnings(ticker, field, gaps, lookahead, ignore_invalid_symbol, currency)`: earnings per share of
|
|
4443
|
+
* the last release (`earnings.actual`, default, `earnings.estimate` or `earnings.standardized`), from the bar after the
|
|
4444
|
+
* period of the chart timeframe it was published in (the next day on a daily chart).
|
|
4445
|
+
*/
|
|
4446
|
+
function earningsCall(...args: EventRequestCall): Series {
|
|
4447
|
+
const a = namedArguments('request.earnings', DIVIDENDS_PARAMETERS, args);
|
|
4448
|
+
unsupportedSecurityArgs('request.earnings', a[5], undefined);
|
|
4449
|
+
const ticker = (a[0] as string | undefined) ?? '';
|
|
4450
|
+
const field = (a[1] as string | undefined) ?? earnings.actual;
|
|
4451
|
+
if (field !== earnings.actual && field !== earnings.estimate && field !== earnings.standardized) {
|
|
4452
|
+
throw new Error(`request.earnings(): unknown field "${field}": earnings.actual, earnings.estimate or earnings.standardized.`);
|
|
4453
|
+
}
|
|
4454
|
+
// announced releases still to come have no values yet
|
|
4455
|
+
const list = (symbolEvents(ticker).earnings ?? []).filter((e) => e.time <= runNow);
|
|
4456
|
+
return eventSeries(list.map((e) => e.time), eventField(list, field, 'request.earnings', ticker), a[2] as string | undefined, a[3] as string | undefined);
|
|
4457
|
+
}
|
|
4458
|
+
|
|
4459
|
+
export const request = strictNamespace('request', {
|
|
4460
|
+
security: securityCall,
|
|
4461
|
+
security_lower_tf: securityLowerTfCall,
|
|
4462
|
+
seed: seedCall,
|
|
4463
|
+
dividends: dividendsCall,
|
|
4464
|
+
splits: splitsCall,
|
|
4465
|
+
earnings: earningsCall,
|
|
4466
|
+
});
|
|
3969
4467
|
|
|
3970
4468
|
// ── Drawing objects ──────────────────────────────────────────────────────────
|
|
3971
4469
|
// The drawing namespaces come from this bundle so that they share the registry that
|
|
@@ -3988,7 +4486,7 @@ export interface LabelNewArgs {
|
|
|
3988
4486
|
y?: Numeric;
|
|
3989
4487
|
point?: ChartPoint;
|
|
3990
4488
|
text?: string;
|
|
3991
|
-
xloc?: 'bar_index' | 'bar_time';
|
|
4489
|
+
xloc?: 'bar_index' | 'bar_time' | 'pane';
|
|
3992
4490
|
yloc?: 'price' | 'abovebar' | 'belowbar';
|
|
3993
4491
|
color?: Colour;
|
|
3994
4492
|
style?: NonNullable<Label['style']>;
|
|
@@ -4009,7 +4507,7 @@ export interface LineNewArgs {
|
|
|
4009
4507
|
y2?: Numeric;
|
|
4010
4508
|
first_point?: ChartPoint;
|
|
4011
4509
|
second_point?: ChartPoint;
|
|
4012
|
-
xloc?: 'bar_index' | 'bar_time';
|
|
4510
|
+
xloc?: 'bar_index' | 'bar_time' | 'pane';
|
|
4013
4511
|
extend?: 'none' | 'left' | 'right' | 'both';
|
|
4014
4512
|
color?: Colour;
|
|
4015
4513
|
style?: 'solid' | 'dotted' | 'dashed' | 'arrow_left' | 'arrow_right' | 'arrow_both';
|
|
@@ -4029,7 +4527,7 @@ export interface BoxNewArgs {
|
|
|
4029
4527
|
border_width?: Numeric;
|
|
4030
4528
|
border_style?: 'solid' | 'dotted' | 'dashed';
|
|
4031
4529
|
extend?: 'none' | 'left' | 'right' | 'both';
|
|
4032
|
-
xloc?: 'bar_index' | 'bar_time';
|
|
4530
|
+
xloc?: 'bar_index' | 'bar_time' | 'pane';
|
|
4033
4531
|
bgcolor?: Colour;
|
|
4034
4532
|
text?: string;
|
|
4035
4533
|
text_size?: string | number;
|
|
@@ -4078,7 +4576,7 @@ export interface PolylineNewArgs {
|
|
|
4078
4576
|
points?: ChartPoint[];
|
|
4079
4577
|
curved?: boolean;
|
|
4080
4578
|
closed?: boolean;
|
|
4081
|
-
xloc?: 'bar_index' | 'bar_time';
|
|
4579
|
+
xloc?: 'bar_index' | 'bar_time' | 'pane';
|
|
4082
4580
|
line_color?: Colour;
|
|
4083
4581
|
fill_color?: Colour | null;
|
|
4084
4582
|
line_style?: 'solid' | 'dotted' | 'dashed';
|
|
@@ -4174,6 +4672,38 @@ export const chart = {
|
|
|
4174
4672
|
get bg_color(): string {
|
|
4175
4673
|
return chartText('backgroundColor', 'chart.bg_color');
|
|
4176
4674
|
},
|
|
4675
|
+
/** Time (ms) of the first bar in view (PineScript `chart.left_visible_bar_time`), from the chart context; without it,
|
|
4676
|
+
* of the first bar. */
|
|
4677
|
+
get left_visible_bar_time(): number {
|
|
4678
|
+
return visibleBarTime(chartCtx.leftVisibleBarTime, 0);
|
|
4679
|
+
},
|
|
4680
|
+
/** Time (ms) of the last bar in view (PineScript `chart.right_visible_bar_time`), from the chart context; without it,
|
|
4681
|
+
* of the last bar. */
|
|
4682
|
+
get right_visible_bar_time(): number {
|
|
4683
|
+
return visibleBarTime(chartCtx.rightVisibleBarTime, ctxBars.bars.length - 1);
|
|
4684
|
+
},
|
|
4685
|
+
/** The chart is not one of the types below (PineScript `chart.is_standard`). */
|
|
4686
|
+
get is_standard(): boolean {
|
|
4687
|
+
return chartTypeIs('standard');
|
|
4688
|
+
},
|
|
4689
|
+
get is_heikinashi(): boolean {
|
|
4690
|
+
return chartTypeIs('heikinashi');
|
|
4691
|
+
},
|
|
4692
|
+
get is_renko(): boolean {
|
|
4693
|
+
return chartTypeIs('renko');
|
|
4694
|
+
},
|
|
4695
|
+
get is_kagi(): boolean {
|
|
4696
|
+
return chartTypeIs('kagi');
|
|
4697
|
+
},
|
|
4698
|
+
get is_linebreak(): boolean {
|
|
4699
|
+
return chartTypeIs('linebreak');
|
|
4700
|
+
},
|
|
4701
|
+
get is_pnf(): boolean {
|
|
4702
|
+
return chartTypeIs('pnf');
|
|
4703
|
+
},
|
|
4704
|
+
get is_range(): boolean {
|
|
4705
|
+
return chartTypeIs('range');
|
|
4706
|
+
},
|
|
4177
4707
|
point: {
|
|
4178
4708
|
...chartPointCore,
|
|
4179
4709
|
now(price?: number): ChartPoint {
|