oakscriptjs 0.20.0 → 0.22.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/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/check/spec.d.ts +1 -1
- package/dist/cjs/check/spec.d.ts.map +1 -1
- package/dist/cjs/check/spec.js +1 -1
- package/dist/cjs/check/spec.js.map +2 -2
- package/dist/cjs/runtime/types.d.ts +9 -4
- package/dist/cjs/runtime/types.d.ts.map +1 -1
- package/dist/cjs/runtime/types.js.map +1 -1
- package/dist/cjs/script/globals.d.ts +4 -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 +237 -11
- package/dist/cjs/script/index.d.ts.map +1 -1
- package/dist/cjs/script/index.js +354 -32
- 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/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/check/spec.d.ts +1 -1
- package/dist/esm/check/spec.d.ts.map +1 -1
- package/dist/esm/check/spec.js +1 -1
- package/dist/esm/check/spec.js.map +1 -1
- package/dist/esm/runtime/types.d.ts +9 -4
- package/dist/esm/runtime/types.d.ts.map +1 -1
- package/dist/esm/script/globals.d.ts +4 -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 +237 -11
- package/dist/esm/script/index.d.ts.map +1 -1
- package/dist/esm/script/index.js +381 -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/package.json +1 -1
- package/skills/oakscript/reference/script-structure.md +12 -2
- package/skills/oakscript/reference/timeframes-symbols.md +27 -0
- package/skills/oakscript/spec.schema.json +2 -1
- package/src/check/harness.ts +27 -0
- package/src/check/spec.ts +1 -1
- package/src/runtime/types.ts +9 -4
- package/src/script/globals.ts +4 -0
- package/src/script/index.ts +581 -46
- package/src/security/events.ts +85 -0
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 {
|
|
@@ -505,7 +506,14 @@ function runBody(
|
|
|
505
506
|
mathCore.resetRandom();
|
|
506
507
|
missingSymbols = [];
|
|
507
508
|
try {
|
|
508
|
-
|
|
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
|
+
}
|
|
509
517
|
if (missingSymbols.length) throw new MissingSymbolDataError(missingSymbols);
|
|
510
518
|
// the outputs read the drawings: not a drawing of the script
|
|
511
519
|
if (inc) incremental.bodyDone();
|
|
@@ -1199,6 +1207,55 @@ export interface NumericInputOptions extends InputOptions {
|
|
|
1199
1207
|
minval?: number;
|
|
1200
1208
|
maxval?: number;
|
|
1201
1209
|
step?: number;
|
|
1210
|
+
/** The values to choose from (the host shows a drop-down list). */
|
|
1211
|
+
options?: number[];
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
/** A field of an enum made with `defineEnum()`: its name and title. `String(field)` is the title, as PineScript
|
|
1215
|
+
* `str.tostring()` of an enum field. */
|
|
1216
|
+
export interface EnumField {
|
|
1217
|
+
readonly name: string;
|
|
1218
|
+
readonly title: string;
|
|
1219
|
+
toString(): string;
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
export interface EnumInputOptions extends InputOptions {
|
|
1223
|
+
/** The fields to choose from (default: every field of the enum). */
|
|
1224
|
+
options?: EnumField[];
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
/** A class, not a plain object: a field passed where the options can be is not read as named arguments. */
|
|
1228
|
+
class EnumFieldValue implements EnumField {
|
|
1229
|
+
constructor(readonly name: string, readonly title: string) {
|
|
1230
|
+
Object.freeze(this);
|
|
1231
|
+
}
|
|
1232
|
+
toString(): string {
|
|
1233
|
+
return this.title;
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
/** The fields of each enum, by field: `input.enum()` lists them from its default. */
|
|
1238
|
+
const enumFieldsOf = new WeakMap<EnumField, readonly EnumField[]>();
|
|
1239
|
+
|
|
1240
|
+
/**
|
|
1241
|
+
* PineScript `enum`: a set of named fields, each with a title (the name when the title is empty).
|
|
1242
|
+
* `const MaType = defineEnum({ sma: "Simple", ema: "Exponential" })`; `MaType.sma.title` is "Simple" and
|
|
1243
|
+
* `input.enum(MaType.sma, "Average")` returns `MaType.sma` or `MaType.ema`. Fields compare with `===`.
|
|
1244
|
+
*/
|
|
1245
|
+
export function defineEnum<K extends string>(fields: Record<K, string>): { readonly [P in K]: EnumField } {
|
|
1246
|
+
if (!isPlainObject(fields) || Object.keys(fields).length === 0) {
|
|
1247
|
+
throw new TypeError('defineEnum(): the fields are an object of names and titles, e.g. { sma: "Simple", ema: "Exponential" }.');
|
|
1248
|
+
}
|
|
1249
|
+
const list: EnumField[] = [];
|
|
1250
|
+
const out: Record<string, EnumField> = {};
|
|
1251
|
+
for (const [name, title] of Object.entries(fields)) {
|
|
1252
|
+
if (title !== undefined && typeof title !== 'string') throw new TypeError(`defineEnum(): the title of "${name}" is a string.`);
|
|
1253
|
+
const field = new EnumFieldValue(name, title || name);
|
|
1254
|
+
list.push(field);
|
|
1255
|
+
out[name] = field;
|
|
1256
|
+
}
|
|
1257
|
+
for (const field of list) enumFieldsOf.set(field, list);
|
|
1258
|
+
return Object.freeze(out) as { readonly [P in K]: EnumField };
|
|
1202
1259
|
}
|
|
1203
1260
|
|
|
1204
1261
|
export interface StringInputOptions extends InputOptions {
|
|
@@ -1230,7 +1287,7 @@ function registerInput<T>(config: Omit<InputConfig, 'id'>, fallbackId: string):
|
|
|
1230
1287
|
|
|
1231
1288
|
function registerNumeric(type: 'int' | 'float', defval: number, title?: string, opts: NumericInputOptions = {}): number {
|
|
1232
1289
|
const v = registerInput<unknown>(
|
|
1233
|
-
{ type, defval, title, min: opts.minval, max: opts.maxval, step: opts.step, ...common(opts) },
|
|
1290
|
+
{ type, defval, title, min: opts.minval, max: opts.maxval, step: opts.step, ...(opts.options ? { options: opts.options } : {}), ...common(opts) },
|
|
1234
1291
|
`input_${type}`
|
|
1235
1292
|
);
|
|
1236
1293
|
return typeof v === 'number' ? v : defval;
|
|
@@ -1242,8 +1299,9 @@ type InputArgs<O, D> = O & { title?: string; defval?: D };
|
|
|
1242
1299
|
const COMMON_INPUT_KEYS = ['tooltip', 'inline', 'group', 'confirm', 'display', 'active'] as const;
|
|
1243
1300
|
/** The PineScript arguments of each input kind (named arguments are checked against them). */
|
|
1244
1301
|
const INPUT_KEYS: Record<string, readonly string[]> = {
|
|
1245
|
-
int: ['defval', 'title', 'minval', 'maxval', 'step', ...COMMON_INPUT_KEYS],
|
|
1246
|
-
float: ['defval', 'title', 'minval', 'maxval', 'step', ...COMMON_INPUT_KEYS],
|
|
1302
|
+
int: ['defval', 'title', 'minval', 'maxval', 'step', 'options', ...COMMON_INPUT_KEYS],
|
|
1303
|
+
float: ['defval', 'title', 'minval', 'maxval', 'step', 'options', ...COMMON_INPUT_KEYS],
|
|
1304
|
+
enum: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],
|
|
1247
1305
|
price: ['defval', 'title', ...COMMON_INPUT_KEYS],
|
|
1248
1306
|
bool: ['defval', 'title', ...COMMON_INPUT_KEYS],
|
|
1249
1307
|
string: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],
|
|
@@ -1355,6 +1413,32 @@ export const input = strictNamespace('input', {
|
|
|
1355
1413
|
const a = inputArgs<number, InputOptions>('price', defval, title, opts);
|
|
1356
1414
|
return registerNumeric('float', a.defval, a.title, a.opts);
|
|
1357
1415
|
},
|
|
1416
|
+
/**
|
|
1417
|
+
* A field of an enum made with `defineEnum()`: `input.enum(MaType.sma, "Average")`. The host lists the fields by
|
|
1418
|
+
* title (`options`: only these fields) and stores the field name; the call returns the field.
|
|
1419
|
+
*/
|
|
1420
|
+
enum<F extends EnumField>(defval: F | InputArgs<EnumInputOptions, F>, title?: string | InputArgs<EnumInputOptions, F>, opts?: EnumInputOptions): F {
|
|
1421
|
+
const a = inputArgs<F, EnumInputOptions>('enum', defval, title, opts);
|
|
1422
|
+
const fields = a.defval === undefined ? undefined : enumFieldsOf.get(a.defval);
|
|
1423
|
+
if (!fields) throw new TypeError('input.enum(): the default is a field of an enum made with defineEnum(), e.g. input.enum(MaType.sma, "Average").');
|
|
1424
|
+
const choices = a.opts.options ?? fields;
|
|
1425
|
+
for (const f of choices) {
|
|
1426
|
+
if (!fields.includes(f)) throw new TypeError('input.enum(): the options are fields of the enum of the default.');
|
|
1427
|
+
}
|
|
1428
|
+
if (!choices.includes(a.defval)) throw new TypeError('input.enum(): the default is one of the options.');
|
|
1429
|
+
const name = registerInput<unknown>(
|
|
1430
|
+
{
|
|
1431
|
+
type: 'enum',
|
|
1432
|
+
defval: a.defval.name,
|
|
1433
|
+
title: a.title,
|
|
1434
|
+
options: choices.map((f) => f.name),
|
|
1435
|
+
optionsTitles: Object.fromEntries(choices.map((f) => [f.name, f.title])),
|
|
1436
|
+
...common(a.opts),
|
|
1437
|
+
},
|
|
1438
|
+
'input_enum'
|
|
1439
|
+
);
|
|
1440
|
+
return (choices.find((f) => f.name === name) ?? a.defval) as F;
|
|
1441
|
+
},
|
|
1358
1442
|
/** Date and time as a UNIX time in milliseconds, e.g. `input.time(timestamp('2024-01-01'), 'Start')`. */
|
|
1359
1443
|
time(defval: number | InputArgs<InputOptions, number>, title?: string | InputArgs<InputOptions, number>, opts?: InputOptions): number {
|
|
1360
1444
|
const a = inputArgs<number, InputOptions>('time', defval, title, opts);
|
|
@@ -1736,12 +1820,13 @@ export function fixnan(source: Series | Array<string | undefined>): Series | Arr
|
|
|
1736
1820
|
}
|
|
1737
1821
|
|
|
1738
1822
|
/** PineScript `na(x)`. On a Series: a Series of 1 / 0, 1 where the value is na (NaN or +/-Infinity, #187). On a
|
|
1739
|
-
* single value (a number of a bar loop, a colour, a drawing): true when it is na.
|
|
1823
|
+
* single value (a number of a bar loop, a colour, a drawing): true when it is na. An empty text is na, as in
|
|
1824
|
+
* PineScript (`na("")`, `na(syminfo.basecurrency)` of a stock). */
|
|
1740
1825
|
export function na(x: Series): Series;
|
|
1741
1826
|
export function na(x: unknown): boolean;
|
|
1742
1827
|
export function na(x: unknown): Series | boolean {
|
|
1743
1828
|
if (x instanceof Series) return Series.fromArray(ctxBars, x.toArray().map((v) => (isNA(v) ? 1 : 0)));
|
|
1744
|
-
return isNA(x);
|
|
1829
|
+
return x === '' || isNA(x);
|
|
1745
1830
|
}
|
|
1746
1831
|
|
|
1747
1832
|
/** PineScript `nz(source, replacement)`; replacement defaults to 0. On a Series: each na value (NaN or +/-Infinity)
|
|
@@ -3122,13 +3207,54 @@ export interface ChartContext {
|
|
|
3122
3207
|
currency?: string;
|
|
3123
3208
|
/**
|
|
3124
3209
|
* Base currency of the symbol (PineScript `syminfo.basecurrency`): "BTC" for BITSTAMP:BTCUSD, BINANCE:BTCUSDT.P and
|
|
3125
|
-
* CME:BTC1!, "EUR" for FX:EURUSD, "" for a stock, an index or CME_MINI:ES1! (#180)
|
|
3210
|
+
* CME:BTC1!, "EUR" for FX:EURUSD, "" for a stock, an index or CME_MINI:ES1! (#180).
|
|
3211
|
+
*
|
|
3212
|
+
* The symbol fields below, like this one: a value; null when the symbol has none (PineScript gives na: "" for a
|
|
3213
|
+
* text, which `na()` takes as na, NaN for a number); left out when the host does not know it (reading it throws).
|
|
3214
|
+
*/
|
|
3215
|
+
basecurrency?: string | null;
|
|
3216
|
+
/**
|
|
3217
|
+
* Root of the symbol (PineScript `syminfo.root`): "BTC" for CME:BTC1!, "ES" for CME_MINI:ES1!, "AAPL" for
|
|
3218
|
+
* NASDAQ:AAPL (#180). Default: the ticker, without the "1!" of a continuous future or the month code and year of a
|
|
3219
|
+
* contract ("ESZ2026" of a `symbolType` "futures").
|
|
3126
3220
|
*/
|
|
3127
|
-
|
|
3128
|
-
/** Root of the symbol (PineScript `syminfo.root`): "BTC" for CME:BTC1!, "ES" for CME_MINI:ES1!, "AAPL" for NASDAQ:AAPL (#180) */
|
|
3129
|
-
root?: string;
|
|
3221
|
+
root?: string | null;
|
|
3130
3222
|
/** Description of the symbol (PineScript `syminfo.description`): "Apple Inc." for NASDAQ:AAPL, "Bitcoin / U.S. dollar" for BITSTAMP:BTCUSD (#184) */
|
|
3131
|
-
description?: string;
|
|
3223
|
+
description?: string | null;
|
|
3224
|
+
/** Prefix of the ticker id (PineScript `syminfo.prefix`), default: the part of `tickerid` before ":" */
|
|
3225
|
+
prefix?: string | null;
|
|
3226
|
+
/** Ticker without its prefix (PineScript `syminfo.ticker`), default: the part of `tickerid` after ":" */
|
|
3227
|
+
ticker?: string;
|
|
3228
|
+
/** The chart's own symbol (PineScript `syminfo.main_tickerid`, the same inside `request.security`); default `tickerid` */
|
|
3229
|
+
mainTickerid?: string;
|
|
3230
|
+
/** Two-letter code of the country the symbol trades in (PineScript `syminfo.country`): "US", "IN" */
|
|
3231
|
+
country?: string | null;
|
|
3232
|
+
/** Contract a continuous future stands for (PineScript `syminfo.current_contract`): "ESZ2026" for CME_MINI:ES1! */
|
|
3233
|
+
currentContract?: string | null;
|
|
3234
|
+
/** Last trading day of a future's contract, in ms (PineScript `syminfo.expiration_date`) */
|
|
3235
|
+
expirationDate?: number | null;
|
|
3236
|
+
/** PineScript `syminfo.sector` and `syminfo.industry` of a company */
|
|
3237
|
+
sector?: string | null;
|
|
3238
|
+
industry?: string | null;
|
|
3239
|
+
/** PineScript `syminfo.isin`: "US0378331005" for NASDAQ:AAPL */
|
|
3240
|
+
isin?: string | null;
|
|
3241
|
+
/** Unit of the volume (PineScript `syminfo.volumetype`): "base" (crypto: in the base currency), "quote", "tick", "n/a" */
|
|
3242
|
+
volumetype?: string | null;
|
|
3243
|
+
/** PineScript `syminfo.employees`, `syminfo.shareholders`, `syminfo.shares_outstanding_total` / `_float` */
|
|
3244
|
+
employees?: number | null;
|
|
3245
|
+
shareholders?: number | null;
|
|
3246
|
+
sharesOutstandingTotal?: number | null;
|
|
3247
|
+
sharesOutstandingFloat?: number | null;
|
|
3248
|
+
/** Analysts' ratings (PineScript `syminfo.recommendations_*`; `date` in ms) */
|
|
3249
|
+
recommendations?: SymbolRecommendations | null;
|
|
3250
|
+
/** Analysts' price targets (PineScript `syminfo.target_price_*`; `date` in ms) */
|
|
3251
|
+
targetPrice?: SymbolTargetPrice | null;
|
|
3252
|
+
/**
|
|
3253
|
+
* Dividends, splits and earnings of a symbol (PineScript `request.dividends`, `request.splits`, `request.earnings`,
|
|
3254
|
+
* `dividends.future_*`, `earnings.future_*`). Return undefined when they are not loaded: the run then ends with a
|
|
3255
|
+
* {@link MissingSymbolDataError} whose request has `events: true`. Return {} for a symbol without any.
|
|
3256
|
+
*/
|
|
3257
|
+
events?: (symbol: string) => SymbolEvents | undefined;
|
|
3132
3258
|
/** Chart foreground colour (PineScript `chart.fg_color`), e.g. "#DBDBDB" on a dark chart */
|
|
3133
3259
|
foregroundColor?: string;
|
|
3134
3260
|
/** Chart background colour (PineScript `chart.bg_color`), e.g. "#0F0F0F" on a dark chart */
|
|
@@ -3188,12 +3314,108 @@ export type SymbolInfo = Pick<
|
|
|
3188
3314
|
| 'basecurrency'
|
|
3189
3315
|
| 'root'
|
|
3190
3316
|
| 'description'
|
|
3317
|
+
| 'prefix'
|
|
3318
|
+
| 'ticker'
|
|
3319
|
+
| 'country'
|
|
3320
|
+
| 'currentContract'
|
|
3321
|
+
| 'expirationDate'
|
|
3322
|
+
| 'sector'
|
|
3323
|
+
| 'industry'
|
|
3324
|
+
| 'isin'
|
|
3325
|
+
| 'volumetype'
|
|
3326
|
+
| 'employees'
|
|
3327
|
+
| 'shareholders'
|
|
3328
|
+
| 'sharesOutstandingTotal'
|
|
3329
|
+
| 'sharesOutstandingFloat'
|
|
3330
|
+
| 'recommendations'
|
|
3331
|
+
| 'targetPrice'
|
|
3191
3332
|
>;
|
|
3192
3333
|
|
|
3193
|
-
/**
|
|
3334
|
+
/** The symbol fields a {@link SymbolInfo} gives to `syminfo.*` inside `request.security`. */
|
|
3335
|
+
const SYMBOL_INFO_KEYS = [
|
|
3336
|
+
'timezone', 'session', 'regularSession', 'mintick', 'minmove', 'pricescale', 'pointvalue', 'mincontract', 'symbolType',
|
|
3337
|
+
'currency', 'basecurrency', 'root', 'description', 'prefix', 'ticker', 'country', 'currentContract', 'expirationDate',
|
|
3338
|
+
'sector', 'industry', 'isin', 'volumetype', 'employees', 'shareholders', 'sharesOutstandingTotal',
|
|
3339
|
+
'sharesOutstandingFloat', 'recommendations', 'targetPrice',
|
|
3340
|
+
] as const satisfies readonly (keyof SymbolInfo)[];
|
|
3341
|
+
|
|
3342
|
+
/** Analysts' ratings of a symbol: counts of each rating, and the date of the count (ms). */
|
|
3343
|
+
export interface SymbolRecommendations {
|
|
3344
|
+
buy: number;
|
|
3345
|
+
buy_strong: number;
|
|
3346
|
+
hold: number;
|
|
3347
|
+
sell: number;
|
|
3348
|
+
sell_strong: number;
|
|
3349
|
+
total: number;
|
|
3350
|
+
date: number;
|
|
3351
|
+
}
|
|
3352
|
+
|
|
3353
|
+
/** Analysts' price targets of a symbol, their number and the date of the figures (ms). */
|
|
3354
|
+
export interface SymbolTargetPrice {
|
|
3355
|
+
average: number;
|
|
3356
|
+
high: number;
|
|
3357
|
+
low: number;
|
|
3358
|
+
median: number;
|
|
3359
|
+
estimates: number;
|
|
3360
|
+
date: number;
|
|
3361
|
+
}
|
|
3362
|
+
|
|
3363
|
+
/**
|
|
3364
|
+
* A dividend: `time` the ex-date (ms; 00:00 UTC of the day, as PineScript's dividends are stamped), the amount per
|
|
3365
|
+
* share as declared (not adjusted for later splits), net and gross of withholding tax (gross defaults to net).
|
|
3366
|
+
*/
|
|
3367
|
+
export interface DividendEvent {
|
|
3368
|
+
time: number;
|
|
3369
|
+
net: number;
|
|
3370
|
+
gross?: number;
|
|
3371
|
+
/** Payment date (ms) */
|
|
3372
|
+
payDate?: number | null;
|
|
3373
|
+
}
|
|
3374
|
+
|
|
3375
|
+
/** A split from `denominator` shares to `numerator` (4 and 1 for a 4-for-1 split); `time` its date (ms, 00:00 UTC). */
|
|
3376
|
+
export interface SplitEvent {
|
|
3377
|
+
time: number;
|
|
3378
|
+
numerator: number;
|
|
3379
|
+
denominator: number;
|
|
3380
|
+
}
|
|
3381
|
+
|
|
3382
|
+
/**
|
|
3383
|
+
* An earnings release: `time` when it was published (ms; a release after the close is after the session's close). The
|
|
3384
|
+
* values per share are adjusted for later splits, as PineScript gives them. A value the host does not have is left
|
|
3385
|
+
* out; a script that asks for it then stops with an error.
|
|
3386
|
+
*/
|
|
3387
|
+
export interface EarningsEvent {
|
|
3388
|
+
time: number;
|
|
3389
|
+
/** Reported earnings per share (`earnings.actual`), the analysts' estimate (`earnings.estimate`), standardized
|
|
3390
|
+
* earnings per share (`earnings.standardized`) */
|
|
3391
|
+
actual?: number | null;
|
|
3392
|
+
estimate?: number | null;
|
|
3393
|
+
standardized?: number | null;
|
|
3394
|
+
/** Estimated revenue (`earnings.future_revenue`) and the end of the fiscal period (ms) */
|
|
3395
|
+
revenueEstimate?: number | null;
|
|
3396
|
+
periodEnd?: number | null;
|
|
3397
|
+
}
|
|
3398
|
+
|
|
3399
|
+
/** Events of a symbol, oldest first. */
|
|
3400
|
+
export interface SymbolEvents {
|
|
3401
|
+
dividends?: DividendEvent[];
|
|
3402
|
+
splits?: SplitEvent[];
|
|
3403
|
+
earnings?: EarningsEvent[];
|
|
3404
|
+
/**
|
|
3405
|
+
* The lists hold the announced events still to come (`dividends.future_*`, `earnings.future_*` read them): without
|
|
3406
|
+
* it the future values are not known and reading them throws.
|
|
3407
|
+
*/
|
|
3408
|
+
future?: { dividends?: boolean; earnings?: boolean };
|
|
3409
|
+
}
|
|
3410
|
+
|
|
3411
|
+
/**
|
|
3412
|
+
* A request of `request.security` for another symbol whose bars the host has not given, or (`events`) of
|
|
3413
|
+
* `request.dividends` / `request.splits` / `request.earnings` for a symbol whose events it has not given.
|
|
3414
|
+
*/
|
|
3194
3415
|
export interface SymbolDataRequest {
|
|
3195
3416
|
symbol: string;
|
|
3196
3417
|
timeframe: string;
|
|
3418
|
+
events?: boolean;
|
|
3197
3419
|
}
|
|
3198
3420
|
|
|
3199
3421
|
/**
|
|
@@ -3202,9 +3424,13 @@ export interface SymbolDataRequest {
|
|
|
3202
3424
|
*/
|
|
3203
3425
|
export class MissingSymbolDataError extends Error {
|
|
3204
3426
|
constructor(readonly requests: SymbolDataRequest[]) {
|
|
3427
|
+
const bars = requests.filter((r) => !r.events);
|
|
3428
|
+
const events = requests.filter((r) => r.events);
|
|
3205
3429
|
super(
|
|
3206
|
-
|
|
3207
|
-
'pass them with ChartContext.bars
|
|
3430
|
+
[
|
|
3431
|
+
bars.length ? `request.security needs the bars of ${bars.map((r) => `${r.symbol} (${r.timeframe})`).join(', ')}: pass them with ChartContext.bars.` : '',
|
|
3432
|
+
events.length ? `The script needs the events of ${events.map((r) => r.symbol).join(', ')}: pass them with ChartContext.events.` : '',
|
|
3433
|
+
].filter(Boolean).join(' ')
|
|
3208
3434
|
);
|
|
3209
3435
|
this.name = 'MissingSymbolDataError';
|
|
3210
3436
|
}
|
|
@@ -3293,9 +3519,23 @@ function symbolProperty(key: 'mintick' | 'pointvalue' | 'mincontract'): number {
|
|
|
3293
3519
|
return value;
|
|
3294
3520
|
}
|
|
3295
3521
|
|
|
3296
|
-
/** A text value of the chart or the symbol that the host passes in the chart context. */
|
|
3522
|
+
/** A text value of the chart or the symbol that the host passes in the chart context; null (none) is "". */
|
|
3297
3523
|
function chartText(
|
|
3298
|
-
key:
|
|
3524
|
+
key:
|
|
3525
|
+
| 'symbolType'
|
|
3526
|
+
| 'currency'
|
|
3527
|
+
| 'basecurrency'
|
|
3528
|
+
| 'root'
|
|
3529
|
+
| 'description'
|
|
3530
|
+
| 'foregroundColor'
|
|
3531
|
+
| 'backgroundColor'
|
|
3532
|
+
| 'prefix'
|
|
3533
|
+
| 'country'
|
|
3534
|
+
| 'currentContract'
|
|
3535
|
+
| 'sector'
|
|
3536
|
+
| 'industry'
|
|
3537
|
+
| 'isin'
|
|
3538
|
+
| 'volumetype',
|
|
3299
3539
|
name: string
|
|
3300
3540
|
): string {
|
|
3301
3541
|
collector();
|
|
@@ -3303,7 +3543,61 @@ function chartText(
|
|
|
3303
3543
|
if (value === undefined) {
|
|
3304
3544
|
throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);
|
|
3305
3545
|
}
|
|
3306
|
-
|
|
3546
|
+
// PineScript's na text is "" (`na("")` is true)
|
|
3547
|
+
return value ?? '';
|
|
3548
|
+
}
|
|
3549
|
+
|
|
3550
|
+
/** A number of the symbol that the host passes in the chart context; null (none) is na. */
|
|
3551
|
+
function symbolNumber(
|
|
3552
|
+
key: 'expirationDate' | 'employees' | 'shareholders' | 'sharesOutstandingTotal' | 'sharesOutstandingFloat',
|
|
3553
|
+
name: string
|
|
3554
|
+
): number {
|
|
3555
|
+
collector();
|
|
3556
|
+
const value = chartCtx[key];
|
|
3557
|
+
if (value === undefined) {
|
|
3558
|
+
throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);
|
|
3559
|
+
}
|
|
3560
|
+
return value ?? NaN;
|
|
3561
|
+
}
|
|
3562
|
+
|
|
3563
|
+
/** A value of the analysts' figures of the symbol (`recommendations`, `targetPrice`); null (none) is na. */
|
|
3564
|
+
function analystNumber<K extends 'recommendations' | 'targetPrice'>(
|
|
3565
|
+
key: K,
|
|
3566
|
+
field: keyof NonNullable<ChartContext[K]>,
|
|
3567
|
+
name: string
|
|
3568
|
+
): number {
|
|
3569
|
+
collector();
|
|
3570
|
+
const group = chartCtx[key];
|
|
3571
|
+
if (group === undefined) {
|
|
3572
|
+
throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);
|
|
3573
|
+
}
|
|
3574
|
+
return group === null ? NaN : ((group as unknown as Record<string, number>)[field as string] ?? NaN);
|
|
3575
|
+
}
|
|
3576
|
+
|
|
3577
|
+
/** The ticker id of the chart (or of the symbol of `request.security`); throws when not known. */
|
|
3578
|
+
function chartTickerid(): string {
|
|
3579
|
+
collector();
|
|
3580
|
+
if (!chartCtx.tickerid) {
|
|
3581
|
+
throw new Error('The chart symbol is not known: pass it as executeScript(body, bars, inputs, { tickerid }).');
|
|
3582
|
+
}
|
|
3583
|
+
return chartCtx.tickerid;
|
|
3584
|
+
}
|
|
3585
|
+
|
|
3586
|
+
/** A ticker id cut at its prefix: ["NASDAQ", "AAPL"], ["", "AAPL"] without one. */
|
|
3587
|
+
function splitTickerid(tickerid: string): [string, string] {
|
|
3588
|
+
const at = tickerid.indexOf(':');
|
|
3589
|
+
return at < 0 ? ['', tickerid] : [tickerid.slice(0, at), tickerid.slice(at + 1)];
|
|
3590
|
+
}
|
|
3591
|
+
|
|
3592
|
+
/** Month codes of futures contracts (F = January ... Z = December). */
|
|
3593
|
+
const CONTRACT_SUFFIX = /^(.+?)[FGHJKMNQUVXZ](\d{4}|\d{2})$/;
|
|
3594
|
+
|
|
3595
|
+
/** Root of a ticker: without the "1!" of a continuous future, or the month code and year of a future's contract. */
|
|
3596
|
+
function tickerRoot(ticker: string, symbolType: string | undefined): string {
|
|
3597
|
+
const continuous = /^(.+?)\d+!$/.exec(ticker);
|
|
3598
|
+
if (continuous) return continuous[1]!;
|
|
3599
|
+
const contract = symbolType === 'futures' ? CONTRACT_SUFFIX.exec(ticker) : null;
|
|
3600
|
+
return contract ? contract[1]! : ticker;
|
|
3307
3601
|
}
|
|
3308
3602
|
|
|
3309
3603
|
/** A visible range value: the chart context's, else the time of bar `index` (NaN without bars). */
|
|
@@ -3329,9 +3623,8 @@ function symbolScale(): [number, number] {
|
|
|
3329
3623
|
}
|
|
3330
3624
|
|
|
3331
3625
|
/**
|
|
3332
|
-
* PineScript `syminfo
|
|
3333
|
-
*
|
|
3334
|
-
* `syminfo.currency`, `syminfo.basecurrency`, `syminfo.root` and `syminfo.description`, from the chart context.
|
|
3626
|
+
* PineScript `syminfo.*`, from the chart context (inside `request.security`, the requested symbol's). A field the
|
|
3627
|
+
* symbol has none of is na ("" for a text); a field the host did not give throws.
|
|
3335
3628
|
*/
|
|
3336
3629
|
export const syminfo = {
|
|
3337
3630
|
get mintick(): number {
|
|
@@ -3353,11 +3646,19 @@ export const syminfo = {
|
|
|
3353
3646
|
return exchangeTimezone();
|
|
3354
3647
|
},
|
|
3355
3648
|
get tickerid(): string {
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
return chartCtx.
|
|
3649
|
+
return chartTickerid();
|
|
3650
|
+
},
|
|
3651
|
+
get main_tickerid(): string {
|
|
3652
|
+
const id = chartTickerid();
|
|
3653
|
+
return chartCtx.mainTickerid ?? id;
|
|
3654
|
+
},
|
|
3655
|
+
get ticker(): string {
|
|
3656
|
+
const id = chartTickerid();
|
|
3657
|
+
return chartCtx.ticker ?? splitTickerid(id)[1];
|
|
3658
|
+
},
|
|
3659
|
+
get prefix(): string {
|
|
3660
|
+
const id = chartTickerid();
|
|
3661
|
+
return chartCtx.prefix === undefined ? splitTickerid(id)[0] : (chartCtx.prefix ?? '');
|
|
3361
3662
|
},
|
|
3362
3663
|
get session(): string {
|
|
3363
3664
|
collector();
|
|
@@ -3373,11 +3674,84 @@ export const syminfo = {
|
|
|
3373
3674
|
return chartText('basecurrency', 'syminfo.basecurrency');
|
|
3374
3675
|
},
|
|
3375
3676
|
get root(): string {
|
|
3376
|
-
return chartText('root', 'syminfo.root');
|
|
3677
|
+
if (chartCtx.root !== undefined) return chartText('root', 'syminfo.root');
|
|
3678
|
+
return tickerRoot(syminfo.ticker, chartCtx.symbolType);
|
|
3377
3679
|
},
|
|
3378
3680
|
get description(): string {
|
|
3379
3681
|
return chartText('description', 'syminfo.description');
|
|
3380
3682
|
},
|
|
3683
|
+
get country(): string {
|
|
3684
|
+
return chartText('country', 'syminfo.country');
|
|
3685
|
+
},
|
|
3686
|
+
get current_contract(): string {
|
|
3687
|
+
return chartText('currentContract', 'syminfo.current_contract');
|
|
3688
|
+
},
|
|
3689
|
+
get expiration_date(): number {
|
|
3690
|
+
return symbolNumber('expirationDate', 'syminfo.expiration_date');
|
|
3691
|
+
},
|
|
3692
|
+
get sector(): string {
|
|
3693
|
+
return chartText('sector', 'syminfo.sector');
|
|
3694
|
+
},
|
|
3695
|
+
get industry(): string {
|
|
3696
|
+
return chartText('industry', 'syminfo.industry');
|
|
3697
|
+
},
|
|
3698
|
+
get isin(): string {
|
|
3699
|
+
return chartText('isin', 'syminfo.isin');
|
|
3700
|
+
},
|
|
3701
|
+
get volumetype(): string {
|
|
3702
|
+
return chartText('volumetype', 'syminfo.volumetype');
|
|
3703
|
+
},
|
|
3704
|
+
get employees(): number {
|
|
3705
|
+
return symbolNumber('employees', 'syminfo.employees');
|
|
3706
|
+
},
|
|
3707
|
+
get shareholders(): number {
|
|
3708
|
+
return symbolNumber('shareholders', 'syminfo.shareholders');
|
|
3709
|
+
},
|
|
3710
|
+
get shares_outstanding_total(): number {
|
|
3711
|
+
return symbolNumber('sharesOutstandingTotal', 'syminfo.shares_outstanding_total');
|
|
3712
|
+
},
|
|
3713
|
+
get shares_outstanding_float(): number {
|
|
3714
|
+
return symbolNumber('sharesOutstandingFloat', 'syminfo.shares_outstanding_float');
|
|
3715
|
+
},
|
|
3716
|
+
get recommendations_buy(): number {
|
|
3717
|
+
return analystNumber('recommendations', 'buy', 'syminfo.recommendations_buy');
|
|
3718
|
+
},
|
|
3719
|
+
get recommendations_buy_strong(): number {
|
|
3720
|
+
return analystNumber('recommendations', 'buy_strong', 'syminfo.recommendations_buy_strong');
|
|
3721
|
+
},
|
|
3722
|
+
get recommendations_hold(): number {
|
|
3723
|
+
return analystNumber('recommendations', 'hold', 'syminfo.recommendations_hold');
|
|
3724
|
+
},
|
|
3725
|
+
get recommendations_sell(): number {
|
|
3726
|
+
return analystNumber('recommendations', 'sell', 'syminfo.recommendations_sell');
|
|
3727
|
+
},
|
|
3728
|
+
get recommendations_sell_strong(): number {
|
|
3729
|
+
return analystNumber('recommendations', 'sell_strong', 'syminfo.recommendations_sell_strong');
|
|
3730
|
+
},
|
|
3731
|
+
get recommendations_total(): number {
|
|
3732
|
+
return analystNumber('recommendations', 'total', 'syminfo.recommendations_total');
|
|
3733
|
+
},
|
|
3734
|
+
get recommendations_date(): number {
|
|
3735
|
+
return analystNumber('recommendations', 'date', 'syminfo.recommendations_date');
|
|
3736
|
+
},
|
|
3737
|
+
get target_price_average(): number {
|
|
3738
|
+
return analystNumber('targetPrice', 'average', 'syminfo.target_price_average');
|
|
3739
|
+
},
|
|
3740
|
+
get target_price_high(): number {
|
|
3741
|
+
return analystNumber('targetPrice', 'high', 'syminfo.target_price_high');
|
|
3742
|
+
},
|
|
3743
|
+
get target_price_low(): number {
|
|
3744
|
+
return analystNumber('targetPrice', 'low', 'syminfo.target_price_low');
|
|
3745
|
+
},
|
|
3746
|
+
get target_price_median(): number {
|
|
3747
|
+
return analystNumber('targetPrice', 'median', 'syminfo.target_price_median');
|
|
3748
|
+
},
|
|
3749
|
+
get target_price_estimates(): number {
|
|
3750
|
+
return analystNumber('targetPrice', 'estimates', 'syminfo.target_price_estimates');
|
|
3751
|
+
},
|
|
3752
|
+
get target_price_date(): number {
|
|
3753
|
+
return analystNumber('targetPrice', 'date', 'syminfo.target_price_date');
|
|
3754
|
+
},
|
|
3381
3755
|
};
|
|
3382
3756
|
|
|
3383
3757
|
/** A calendar function: `(time, timezone?)` on a UNIX time or on a Series of times. */
|
|
@@ -3809,25 +4183,11 @@ function runExternal<T extends SecurityValue>(
|
|
|
3809
4183
|
let result: T;
|
|
3810
4184
|
let values: number[][];
|
|
3811
4185
|
ctxBars.setAll(bars);
|
|
3812
|
-
// the expression sees that symbol: its ticker, timeframe, calendar and properties
|
|
3813
|
-
|
|
3814
|
-
|
|
3815
|
-
|
|
3816
|
-
|
|
3817
|
-
timezone: info.timezone,
|
|
3818
|
-
session: info.session,
|
|
3819
|
-
regularSession: info.regularSession,
|
|
3820
|
-
mintick: info.mintick,
|
|
3821
|
-
minmove: info.minmove,
|
|
3822
|
-
pricescale: info.pricescale,
|
|
3823
|
-
pointvalue: info.pointvalue,
|
|
3824
|
-
mincontract: info.mincontract,
|
|
3825
|
-
symbolType: info.symbolType,
|
|
3826
|
-
currency: info.currency,
|
|
3827
|
-
basecurrency: info.basecurrency,
|
|
3828
|
-
root: info.root,
|
|
3829
|
-
description: info.description,
|
|
3830
|
-
};
|
|
4186
|
+
// the expression sees that symbol: its ticker, timeframe, calendar and properties (the chart's own symbol stays the
|
|
4187
|
+
// main one)
|
|
4188
|
+
const seen: ChartContext = { ...chartCtx, tickerid: symbol, timeframe: tf, mainTickerid: chartCtx.mainTickerid ?? chartCtx.tickerid };
|
|
4189
|
+
for (const key of SYMBOL_INFO_KEYS) (seen as Record<string, unknown>)[key] = info[key];
|
|
4190
|
+
chartCtx = seen;
|
|
3831
4191
|
try {
|
|
3832
4192
|
result = expression();
|
|
3833
4193
|
const parts = Array.isArray(result) ? result : [result];
|
|
@@ -4004,7 +4364,182 @@ function seedCall<T extends SecurityValue>(
|
|
|
4004
4364
|
return seed(a[0] as string, a[1] as string, a[2] as () => T, a[3] as boolean | undefined);
|
|
4005
4365
|
}
|
|
4006
4366
|
|
|
4007
|
-
|
|
4367
|
+
// ── request.dividends / request.splits / request.earnings (#211) ─────────────
|
|
4368
|
+
|
|
4369
|
+
/** The events of `ticker` ("" or the chart's: the chart symbol); {} while the host has not given them (the run ends with
|
|
4370
|
+
* a MissingSymbolDataError). */
|
|
4371
|
+
function symbolEvents(ticker: string): SymbolEvents {
|
|
4372
|
+
collector();
|
|
4373
|
+
const symbol = ticker === '' ? chartTickerid() : ticker;
|
|
4374
|
+
const events = chartCtx.events?.(symbol);
|
|
4375
|
+
if (events === undefined) {
|
|
4376
|
+
if (!missingSymbols.some((r) => r.events && r.symbol === symbol)) missingSymbols.push({ symbol, timeframe: '', events: true });
|
|
4377
|
+
return {};
|
|
4378
|
+
}
|
|
4379
|
+
return events;
|
|
4380
|
+
}
|
|
4381
|
+
|
|
4382
|
+
/** One value of each event; throws when no event has it (the host does not have it), na where one has none. */
|
|
4383
|
+
function eventField<E extends object>(list: E[], field: keyof E, name: string, ticker: string): number[] {
|
|
4384
|
+
if (list.length && list.every((e) => e[field] === undefined)) {
|
|
4385
|
+
throw new Error(`${name}: the ${String(field)} values of ${ticker || 'the chart symbol'} are not known.`);
|
|
4386
|
+
}
|
|
4387
|
+
return list.map((e) => {
|
|
4388
|
+
const v = e[field] as unknown;
|
|
4389
|
+
return typeof v === 'number' ? v : NaN;
|
|
4390
|
+
});
|
|
4391
|
+
}
|
|
4392
|
+
|
|
4393
|
+
/** A Series of event values on the chart bars, placed by PineScript's rules (see `security/events`). */
|
|
4394
|
+
function eventSeries(times: number[], values: number[], gaps: string | undefined, lookahead: string | undefined): Series {
|
|
4395
|
+
incremental.nonIncremental('request.dividends / splits / earnings');
|
|
4396
|
+
const opens = ctxBars.bars.map(barTime);
|
|
4397
|
+
const tf = chartTimeframe().period;
|
|
4398
|
+
const span = timeframeCore.info(tf).isticks ? 0 : timeframeCore.in_seconds(tf) * 1000;
|
|
4399
|
+
const { bars } = sessionBars();
|
|
4400
|
+
// a bar without a session period closes where the next one opens
|
|
4401
|
+
const closes = opens.map((t, i) => {
|
|
4402
|
+
const c = bars.closeOf(t, tf);
|
|
4403
|
+
return Number.isFinite(c) ? c : (opens[i + 1] ?? t + span);
|
|
4404
|
+
});
|
|
4405
|
+
const order = times.map((_, i) => i).sort((a, b) => times[a]! - times[b]!);
|
|
4406
|
+
const events = order.map((i) => ({ time: times[i]!, value: values[i]! }));
|
|
4407
|
+
return Series.fromArray(
|
|
4408
|
+
ctxBars,
|
|
4409
|
+
eventsOnBars(opens, closes, tf, events, { gaps: gaps === barmerge.gaps_on, lookahead: lookahead === barmerge.lookahead_on })
|
|
4410
|
+
);
|
|
4411
|
+
}
|
|
4412
|
+
|
|
4413
|
+
/** PineScript `dividends.*`: the fields of `request.dividends` and the next announced dividend of the chart symbol. */
|
|
4414
|
+
export const dividends = {
|
|
4415
|
+
net: 'net',
|
|
4416
|
+
gross: 'gross',
|
|
4417
|
+
/** Amount of the next dividend (net), na when none is announced */
|
|
4418
|
+
get future_amount(): number {
|
|
4419
|
+
return nextDividend()?.net ?? NaN;
|
|
4420
|
+
},
|
|
4421
|
+
/** Ex-date of the next dividend (ms) */
|
|
4422
|
+
get future_ex_date(): number {
|
|
4423
|
+
return nextDividend()?.time ?? NaN;
|
|
4424
|
+
},
|
|
4425
|
+
/** Payment date of the next dividend (ms) */
|
|
4426
|
+
get future_pay_date(): number {
|
|
4427
|
+
return nextDividend()?.payDate ?? NaN;
|
|
4428
|
+
},
|
|
4429
|
+
} as const;
|
|
4430
|
+
|
|
4431
|
+
/** PineScript `splits.*`: the fields of `request.splits`. */
|
|
4432
|
+
export const splits = { numerator: 'numerator', denominator: 'denominator' } as const;
|
|
4433
|
+
|
|
4434
|
+
/** PineScript `earnings.*`: the fields of `request.earnings` and the next earnings release of the chart symbol. */
|
|
4435
|
+
export const earnings = {
|
|
4436
|
+
actual: 'actual',
|
|
4437
|
+
estimate: 'estimate',
|
|
4438
|
+
standardized: 'standardized',
|
|
4439
|
+
/** Estimated earnings per share of the next release */
|
|
4440
|
+
get future_eps(): number {
|
|
4441
|
+
return nextEarnings()?.estimate ?? NaN;
|
|
4442
|
+
},
|
|
4443
|
+
/** Estimated revenue of the next release */
|
|
4444
|
+
get future_revenue(): number {
|
|
4445
|
+
return nextEarnings()?.revenueEstimate ?? NaN;
|
|
4446
|
+
},
|
|
4447
|
+
/** Time of the next release (ms) */
|
|
4448
|
+
get future_time(): number {
|
|
4449
|
+
return nextEarnings()?.time ?? NaN;
|
|
4450
|
+
},
|
|
4451
|
+
/** End of the fiscal period of the next release (ms) */
|
|
4452
|
+
get future_period_end_time(): number {
|
|
4453
|
+
return nextEarnings()?.periodEnd ?? NaN;
|
|
4454
|
+
},
|
|
4455
|
+
} as const;
|
|
4456
|
+
|
|
4457
|
+
/** The first event after the current time of the run in the chart symbol's list, when the host gives the announced ones. */
|
|
4458
|
+
function nextEvent<K extends 'dividends' | 'earnings'>(kind: K): NonNullable<SymbolEvents[K]>[number] | undefined {
|
|
4459
|
+
const events = symbolEvents('');
|
|
4460
|
+
if (!Object.keys(events).length) return undefined;
|
|
4461
|
+
if (!events.future?.[kind]) throw new Error(`${kind}.future_*: the announced ${kind} of ${chartTickerid()} are not known.`);
|
|
4462
|
+
return (events[kind] as Array<{ time: number }> | undefined)?.find((e) => e.time > runNow) as NonNullable<SymbolEvents[K]>[number] | undefined;
|
|
4463
|
+
}
|
|
4464
|
+
const nextDividend = (): DividendEvent | undefined => nextEvent('dividends');
|
|
4465
|
+
const nextEarnings = (): EarningsEvent | undefined => nextEvent('earnings');
|
|
4466
|
+
|
|
4467
|
+
const DIVIDENDS_PARAMETERS = ['ticker', 'field', 'gaps', 'lookahead', 'ignore_invalid_symbol', 'currency'] as const;
|
|
4468
|
+
const SPLITS_PARAMETERS = ['ticker', 'field', 'gaps', 'lookahead', 'ignore_invalid_symbol'] as const;
|
|
4469
|
+
|
|
4470
|
+
/** Named arguments of `request.dividends` / `request.earnings` (`request.splits` has no `currency`). */
|
|
4471
|
+
export interface EventRequestArgs {
|
|
4472
|
+
ticker?: string;
|
|
4473
|
+
field?: string;
|
|
4474
|
+
gaps?: string;
|
|
4475
|
+
lookahead?: string;
|
|
4476
|
+
ignore_invalid_symbol?: boolean;
|
|
4477
|
+
currency?: string;
|
|
4478
|
+
}
|
|
4479
|
+
|
|
4480
|
+
type EventRequestCall =
|
|
4481
|
+
| [ticker: string, field?: string, gaps?: string, lookahead?: string, ignore_invalid_symbol?: boolean, currency?: string]
|
|
4482
|
+
| [ticker: string, field: string, args: EventRequestArgs]
|
|
4483
|
+
| [ticker: string, args: EventRequestArgs]
|
|
4484
|
+
| [args: EventRequestArgs & { ticker: string }];
|
|
4485
|
+
|
|
4486
|
+
/**
|
|
4487
|
+
* PineScript `request.dividends(ticker, field, gaps, lookahead, ignore_invalid_symbol, currency)`: the dividend per
|
|
4488
|
+
* share (`dividends.net`, default, or `dividends.gross`) as declared, from the bar after its ex-date's day (see
|
|
4489
|
+
* `security/events`). na before the first dividend. The events come from `ChartContext.events`.
|
|
4490
|
+
*/
|
|
4491
|
+
function dividendsCall(...args: EventRequestCall): Series {
|
|
4492
|
+
const a = namedArguments('request.dividends', DIVIDENDS_PARAMETERS, args);
|
|
4493
|
+
unsupportedSecurityArgs('request.dividends', a[5], undefined);
|
|
4494
|
+
const ticker = (a[0] as string | undefined) ?? '';
|
|
4495
|
+
const field = (a[1] as string | undefined) ?? dividends.net;
|
|
4496
|
+
if (field !== dividends.net && field !== dividends.gross) throw new Error(`request.dividends(): unknown field "${field}": dividends.net or dividends.gross.`);
|
|
4497
|
+
const list = symbolEvents(ticker).dividends ?? [];
|
|
4498
|
+
const values = field === dividends.gross ? list.map((d) => d.gross ?? d.net) : eventField(list, 'net', 'request.dividends', ticker);
|
|
4499
|
+
return eventSeries(list.map((d) => d.time), values, a[2] as string | undefined, a[3] as string | undefined);
|
|
4500
|
+
}
|
|
4501
|
+
|
|
4502
|
+
/**
|
|
4503
|
+
* PineScript `request.splits(ticker, field, gaps, lookahead, ignore_invalid_symbol)`: the numerator
|
|
4504
|
+
* (`splits.numerator`) or the denominator (`splits.denominator`) of the last split, from the bar after its day.
|
|
4505
|
+
*/
|
|
4506
|
+
function splitsCall(...args: EventRequestCall): Series {
|
|
4507
|
+
const a = namedArguments('request.splits', SPLITS_PARAMETERS, args);
|
|
4508
|
+
const ticker = (a[0] as string | undefined) ?? '';
|
|
4509
|
+
const field = a[1] as string | undefined;
|
|
4510
|
+
if (field !== splits.numerator && field !== splits.denominator) {
|
|
4511
|
+
throw new Error('request.splits(): the field is splits.numerator or splits.denominator.');
|
|
4512
|
+
}
|
|
4513
|
+
const list = symbolEvents(ticker).splits ?? [];
|
|
4514
|
+
return eventSeries(list.map((s) => s.time), eventField(list, field, 'request.splits', ticker), a[2] as string | undefined, a[3] as string | undefined);
|
|
4515
|
+
}
|
|
4516
|
+
|
|
4517
|
+
/**
|
|
4518
|
+
* PineScript `request.earnings(ticker, field, gaps, lookahead, ignore_invalid_symbol, currency)`: earnings per share of
|
|
4519
|
+
* the last release (`earnings.actual`, default, `earnings.estimate` or `earnings.standardized`), from the bar after the
|
|
4520
|
+
* period of the chart timeframe it was published in (the next day on a daily chart).
|
|
4521
|
+
*/
|
|
4522
|
+
function earningsCall(...args: EventRequestCall): Series {
|
|
4523
|
+
const a = namedArguments('request.earnings', DIVIDENDS_PARAMETERS, args);
|
|
4524
|
+
unsupportedSecurityArgs('request.earnings', a[5], undefined);
|
|
4525
|
+
const ticker = (a[0] as string | undefined) ?? '';
|
|
4526
|
+
const field = (a[1] as string | undefined) ?? earnings.actual;
|
|
4527
|
+
if (field !== earnings.actual && field !== earnings.estimate && field !== earnings.standardized) {
|
|
4528
|
+
throw new Error(`request.earnings(): unknown field "${field}": earnings.actual, earnings.estimate or earnings.standardized.`);
|
|
4529
|
+
}
|
|
4530
|
+
// announced releases still to come have no values yet
|
|
4531
|
+
const list = (symbolEvents(ticker).earnings ?? []).filter((e) => e.time <= runNow);
|
|
4532
|
+
return eventSeries(list.map((e) => e.time), eventField(list, field, 'request.earnings', ticker), a[2] as string | undefined, a[3] as string | undefined);
|
|
4533
|
+
}
|
|
4534
|
+
|
|
4535
|
+
export const request = strictNamespace('request', {
|
|
4536
|
+
security: securityCall,
|
|
4537
|
+
security_lower_tf: securityLowerTfCall,
|
|
4538
|
+
seed: seedCall,
|
|
4539
|
+
dividends: dividendsCall,
|
|
4540
|
+
splits: splitsCall,
|
|
4541
|
+
earnings: earningsCall,
|
|
4542
|
+
});
|
|
4008
4543
|
|
|
4009
4544
|
// ── Drawing objects ──────────────────────────────────────────────────────────
|
|
4010
4545
|
// The drawing namespaces come from this bundle so that they share the registry that
|