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.
Files changed (51) hide show
  1. package/dist/cjs/check/harness.d.ts.map +1 -1
  2. package/dist/cjs/check/harness.js +35 -1
  3. package/dist/cjs/check/harness.js.map +2 -2
  4. package/dist/cjs/check/spec.d.ts +1 -1
  5. package/dist/cjs/check/spec.d.ts.map +1 -1
  6. package/dist/cjs/check/spec.js +1 -1
  7. package/dist/cjs/check/spec.js.map +2 -2
  8. package/dist/cjs/runtime/types.d.ts +9 -4
  9. package/dist/cjs/runtime/types.d.ts.map +1 -1
  10. package/dist/cjs/runtime/types.js.map +1 -1
  11. package/dist/cjs/script/globals.d.ts +4 -0
  12. package/dist/cjs/script/globals.d.ts.map +1 -1
  13. package/dist/cjs/script/globals.js.map +1 -1
  14. package/dist/cjs/script/index.d.ts +237 -11
  15. package/dist/cjs/script/index.d.ts.map +1 -1
  16. package/dist/cjs/script/index.js +354 -32
  17. package/dist/cjs/script/index.js.map +3 -3
  18. package/dist/cjs/security/events.d.ts +16 -0
  19. package/dist/cjs/security/events.d.ts.map +1 -0
  20. package/dist/cjs/security/events.js +84 -0
  21. package/dist/cjs/security/events.js.map +7 -0
  22. package/dist/esm/check/harness.d.ts.map +1 -1
  23. package/dist/esm/check/harness.js +25 -0
  24. package/dist/esm/check/harness.js.map +1 -1
  25. package/dist/esm/check/spec.d.ts +1 -1
  26. package/dist/esm/check/spec.d.ts.map +1 -1
  27. package/dist/esm/check/spec.js +1 -1
  28. package/dist/esm/check/spec.js.map +1 -1
  29. package/dist/esm/runtime/types.d.ts +9 -4
  30. package/dist/esm/runtime/types.d.ts.map +1 -1
  31. package/dist/esm/script/globals.d.ts +4 -0
  32. package/dist/esm/script/globals.d.ts.map +1 -1
  33. package/dist/esm/script/globals.js.map +1 -1
  34. package/dist/esm/script/index.d.ts +237 -11
  35. package/dist/esm/script/index.d.ts.map +1 -1
  36. package/dist/esm/script/index.js +381 -38
  37. package/dist/esm/script/index.js.map +1 -1
  38. package/dist/esm/security/events.d.ts +16 -0
  39. package/dist/esm/security/events.d.ts.map +1 -0
  40. package/dist/esm/security/events.js +78 -0
  41. package/dist/esm/security/events.js.map +1 -0
  42. package/package.json +1 -1
  43. package/skills/oakscript/reference/script-structure.md +12 -2
  44. package/skills/oakscript/reference/timeframes-symbols.md +27 -0
  45. package/skills/oakscript/spec.schema.json +2 -1
  46. package/src/check/harness.ts +27 -0
  47. package/src/check/spec.ts +1 -1
  48. package/src/runtime/types.ts +9 -4
  49. package/src/script/globals.ts +4 -0
  50. package/src/script/index.ts +581 -46
  51. package/src/security/events.ts +85 -0
@@ -84,6 +84,7 @@ import { TradingCalendar } from '../session/calendar.js';
84
84
  import { SessionBars, sessionFlags, strayPeriods } from '../session/bars.js';
85
85
  import { afterCompletion, heikinAshi, mapToChart, periodsOf, resample } from '../security/resample.js';
86
86
  import { securityLowerTf, securityOther } from '../security/other.js';
87
+ import { eventsOnBars } from '../security/events.js';
87
88
  import { position } from '../types/index.js';
88
89
  import { STRATEGY_CONSTANTS, STRATEGY_DEFAULTS, STRATEGY_NUMBER_VARIABLES, STRATEGY_TEXT_VARIABLES, } from '../strategy/index.js';
89
90
  import { sessionPeriods } from '../session/context.js';
@@ -228,7 +229,16 @@ function runBody(body, barsInput, inputs, chart, options, inc) {
228
229
  mathCore.resetRandom();
229
230
  missingSymbols = [];
230
231
  try {
231
- body();
232
+ try {
233
+ body();
234
+ }
235
+ catch (err) {
236
+ // An expression of request.security runs on no bar and without the symbol's properties while its bars are not
237
+ // given (syminfo.sector there throws): the run waits for the data, not on the error.
238
+ if (missingSymbols.length && !(err instanceof MissingSymbolDataError))
239
+ throw new MissingSymbolDataError(missingSymbols);
240
+ throw err;
241
+ }
232
242
  if (missingSymbols.length)
233
243
  throw new MissingSymbolDataError(missingSymbols);
234
244
  // the outputs read the drawings: not a drawing of the script
@@ -756,6 +766,43 @@ function declare(c, kind) {
756
766
  }
757
767
  c.declaration = kind;
758
768
  }
769
+ /** A class, not a plain object: a field passed where the options can be is not read as named arguments. */
770
+ class EnumFieldValue {
771
+ name;
772
+ title;
773
+ constructor(name, title) {
774
+ this.name = name;
775
+ this.title = title;
776
+ Object.freeze(this);
777
+ }
778
+ toString() {
779
+ return this.title;
780
+ }
781
+ }
782
+ /** The fields of each enum, by field: `input.enum()` lists them from its default. */
783
+ const enumFieldsOf = new WeakMap();
784
+ /**
785
+ * PineScript `enum`: a set of named fields, each with a title (the name when the title is empty).
786
+ * `const MaType = defineEnum({ sma: "Simple", ema: "Exponential" })`; `MaType.sma.title` is "Simple" and
787
+ * `input.enum(MaType.sma, "Average")` returns `MaType.sma` or `MaType.ema`. Fields compare with `===`.
788
+ */
789
+ export function defineEnum(fields) {
790
+ if (!isPlainObject(fields) || Object.keys(fields).length === 0) {
791
+ throw new TypeError('defineEnum(): the fields are an object of names and titles, e.g. { sma: "Simple", ema: "Exponential" }.');
792
+ }
793
+ const list = [];
794
+ const out = {};
795
+ for (const [name, title] of Object.entries(fields)) {
796
+ if (title !== undefined && typeof title !== 'string')
797
+ throw new TypeError(`defineEnum(): the title of "${name}" is a string.`);
798
+ const field = new EnumFieldValue(name, title || name);
799
+ list.push(field);
800
+ out[name] = field;
801
+ }
802
+ for (const field of list)
803
+ enumFieldsOf.set(field, list);
804
+ return Object.freeze(out);
805
+ }
759
806
  /** The InputConfig fields of the common input options (unset options are left out). */
760
807
  function common(opts) {
761
808
  const out = {};
@@ -784,14 +831,15 @@ function registerInput(config, fallbackId) {
784
831
  return (value === undefined ? config.defval : value);
785
832
  }
786
833
  function registerNumeric(type, defval, title, opts = {}) {
787
- const v = registerInput({ type, defval, title, min: opts.minval, max: opts.maxval, step: opts.step, ...common(opts) }, `input_${type}`);
834
+ const v = registerInput({ type, defval, title, min: opts.minval, max: opts.maxval, step: opts.step, ...(opts.options ? { options: opts.options } : {}), ...common(opts) }, `input_${type}`);
788
835
  return typeof v === 'number' ? v : defval;
789
836
  }
790
837
  const COMMON_INPUT_KEYS = ['tooltip', 'inline', 'group', 'confirm', 'display', 'active'];
791
838
  /** The PineScript arguments of each input kind (named arguments are checked against them). */
792
839
  const INPUT_KEYS = {
793
- int: ['defval', 'title', 'minval', 'maxval', 'step', ...COMMON_INPUT_KEYS],
794
- float: ['defval', 'title', 'minval', 'maxval', 'step', ...COMMON_INPUT_KEYS],
840
+ int: ['defval', 'title', 'minval', 'maxval', 'step', 'options', ...COMMON_INPUT_KEYS],
841
+ float: ['defval', 'title', 'minval', 'maxval', 'step', 'options', ...COMMON_INPUT_KEYS],
842
+ enum: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],
795
843
  price: ['defval', 'title', ...COMMON_INPUT_KEYS],
796
844
  bool: ['defval', 'title', ...COMMON_INPUT_KEYS],
797
845
  string: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],
@@ -900,6 +948,32 @@ export const input = strictNamespace('input', {
900
948
  const a = inputArgs('price', defval, title, opts);
901
949
  return registerNumeric('float', a.defval, a.title, a.opts);
902
950
  },
951
+ /**
952
+ * A field of an enum made with `defineEnum()`: `input.enum(MaType.sma, "Average")`. The host lists the fields by
953
+ * title (`options`: only these fields) and stores the field name; the call returns the field.
954
+ */
955
+ enum(defval, title, opts) {
956
+ const a = inputArgs('enum', defval, title, opts);
957
+ const fields = a.defval === undefined ? undefined : enumFieldsOf.get(a.defval);
958
+ if (!fields)
959
+ throw new TypeError('input.enum(): the default is a field of an enum made with defineEnum(), e.g. input.enum(MaType.sma, "Average").');
960
+ const choices = a.opts.options ?? fields;
961
+ for (const f of choices) {
962
+ if (!fields.includes(f))
963
+ throw new TypeError('input.enum(): the options are fields of the enum of the default.');
964
+ }
965
+ if (!choices.includes(a.defval))
966
+ throw new TypeError('input.enum(): the default is one of the options.');
967
+ const name = registerInput({
968
+ type: 'enum',
969
+ defval: a.defval.name,
970
+ title: a.title,
971
+ options: choices.map((f) => f.name),
972
+ optionsTitles: Object.fromEntries(choices.map((f) => [f.name, f.title])),
973
+ ...common(a.opts),
974
+ }, 'input_enum');
975
+ return (choices.find((f) => f.name === name) ?? a.defval);
976
+ },
903
977
  /** Date and time as a UNIX time in milliseconds, e.g. `input.time(timestamp('2024-01-01'), 'Start')`. */
904
978
  time(defval, title, opts) {
905
979
  const a = inputArgs('time', defval, title, opts);
@@ -1199,7 +1273,7 @@ export function fixnan(source) {
1199
1273
  export function na(x) {
1200
1274
  if (x instanceof Series)
1201
1275
  return Series.fromArray(ctxBars, x.toArray().map((v) => (isNA(v) ? 1 : 0)));
1202
- return isNA(x);
1276
+ return x === '' || isNA(x);
1203
1277
  }
1204
1278
  export function nz(source, replacement = 0) {
1205
1279
  if (source instanceof Series) {
@@ -2254,6 +2328,13 @@ for (const name of [...STRATEGY_NUMBER_VARIABLES, ...STRATEGY_TEXT_VARIABLES]) {
2254
2328
  * ```
2255
2329
  */
2256
2330
  export const strategy = Object.defineProperties(Object.assign((title, options) => declareStrategy(title, options), strategyMembers), variableGetters);
2331
+ /** The symbol fields a {@link SymbolInfo} gives to `syminfo.*` inside `request.security`. */
2332
+ const SYMBOL_INFO_KEYS = [
2333
+ 'timezone', 'session', 'regularSession', 'mintick', 'minmove', 'pricescale', 'pointvalue', 'mincontract', 'symbolType',
2334
+ 'currency', 'basecurrency', 'root', 'description', 'prefix', 'ticker', 'country', 'currentContract', 'expirationDate',
2335
+ 'sector', 'industry', 'isin', 'volumetype', 'employees', 'shareholders', 'sharesOutstandingTotal',
2336
+ 'sharesOutstandingFloat', 'recommendations', 'targetPrice',
2337
+ ];
2257
2338
  /**
2258
2339
  * Thrown by `executeScript` when `request.security` asked for bars of another symbol that `ChartContext.bars` did not
2259
2340
  * give (#179). `requests` lists them all, once each: load them, then run the script again.
@@ -2261,8 +2342,12 @@ export const strategy = Object.defineProperties(Object.assign((title, options) =
2261
2342
  export class MissingSymbolDataError extends Error {
2262
2343
  requests;
2263
2344
  constructor(requests) {
2264
- super(`request.security needs the bars of ${requests.map((r) => `${r.symbol} (${r.timeframe})`).join(', ')}: ` +
2265
- 'pass them with ChartContext.bars.');
2345
+ const bars = requests.filter((r) => !r.events);
2346
+ const events = requests.filter((r) => r.events);
2347
+ super([
2348
+ bars.length ? `request.security needs the bars of ${bars.map((r) => `${r.symbol} (${r.timeframe})`).join(', ')}: pass them with ChartContext.bars.` : '',
2349
+ events.length ? `The script needs the events of ${events.map((r) => r.symbol).join(', ')}: pass them with ChartContext.events.` : '',
2350
+ ].filter(Boolean).join(' '));
2266
2351
  this.requests = requests;
2267
2352
  this.name = 'MissingSymbolDataError';
2268
2353
  }
@@ -2344,14 +2429,56 @@ function symbolProperty(key) {
2344
2429
  }
2345
2430
  return value;
2346
2431
  }
2347
- /** A text value of the chart or the symbol that the host passes in the chart context. */
2432
+ /** A text value of the chart or the symbol that the host passes in the chart context; null (none) is "". */
2348
2433
  function chartText(key, name) {
2349
2434
  collector();
2350
2435
  const value = chartCtx[key];
2351
2436
  if (value === undefined) {
2352
2437
  throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);
2353
2438
  }
2354
- return value;
2439
+ // PineScript's na text is "" (`na("")` is true)
2440
+ return value ?? '';
2441
+ }
2442
+ /** A number of the symbol that the host passes in the chart context; null (none) is na. */
2443
+ function symbolNumber(key, name) {
2444
+ collector();
2445
+ const value = chartCtx[key];
2446
+ if (value === undefined) {
2447
+ throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);
2448
+ }
2449
+ return value ?? NaN;
2450
+ }
2451
+ /** A value of the analysts' figures of the symbol (`recommendations`, `targetPrice`); null (none) is na. */
2452
+ function analystNumber(key, field, name) {
2453
+ collector();
2454
+ const group = chartCtx[key];
2455
+ if (group === undefined) {
2456
+ throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);
2457
+ }
2458
+ return group === null ? NaN : (group[field] ?? NaN);
2459
+ }
2460
+ /** The ticker id of the chart (or of the symbol of `request.security`); throws when not known. */
2461
+ function chartTickerid() {
2462
+ collector();
2463
+ if (!chartCtx.tickerid) {
2464
+ throw new Error('The chart symbol is not known: pass it as executeScript(body, bars, inputs, { tickerid }).');
2465
+ }
2466
+ return chartCtx.tickerid;
2467
+ }
2468
+ /** A ticker id cut at its prefix: ["NASDAQ", "AAPL"], ["", "AAPL"] without one. */
2469
+ function splitTickerid(tickerid) {
2470
+ const at = tickerid.indexOf(':');
2471
+ return at < 0 ? ['', tickerid] : [tickerid.slice(0, at), tickerid.slice(at + 1)];
2472
+ }
2473
+ /** Month codes of futures contracts (F = January ... Z = December). */
2474
+ const CONTRACT_SUFFIX = /^(.+?)[FGHJKMNQUVXZ](\d{4}|\d{2})$/;
2475
+ /** Root of a ticker: without the "1!" of a continuous future, or the month code and year of a future's contract. */
2476
+ function tickerRoot(ticker, symbolType) {
2477
+ const continuous = /^(.+?)\d+!$/.exec(ticker);
2478
+ if (continuous)
2479
+ return continuous[1];
2480
+ const contract = symbolType === 'futures' ? CONTRACT_SUFFIX.exec(ticker) : null;
2481
+ return contract ? contract[1] : ticker;
2355
2482
  }
2356
2483
  /** A visible range value: the chart context's, else the time of bar `index` (NaN without bars). */
2357
2484
  function visibleBarTime(value, index) {
@@ -2375,9 +2502,8 @@ function symbolScale() {
2375
2502
  return [minmove ?? move, scale];
2376
2503
  }
2377
2504
  /**
2378
- * PineScript `syminfo.timezone`, `syminfo.tickerid`, `syminfo.session` (session type), `syminfo.mintick`,
2379
- * `syminfo.minmove`, `syminfo.pricescale`, `syminfo.pointvalue`, `syminfo.mincontract`, `syminfo.type`,
2380
- * `syminfo.currency`, `syminfo.basecurrency`, `syminfo.root` and `syminfo.description`, from the chart context.
2505
+ * PineScript `syminfo.*`, from the chart context (inside `request.security`, the requested symbol's). A field the
2506
+ * symbol has none of is na ("" for a text); a field the host did not give throws.
2381
2507
  */
2382
2508
  export const syminfo = {
2383
2509
  get mintick() {
@@ -2399,11 +2525,19 @@ export const syminfo = {
2399
2525
  return exchangeTimezone();
2400
2526
  },
2401
2527
  get tickerid() {
2402
- collector();
2403
- if (!chartCtx.tickerid) {
2404
- throw new Error('The chart symbol is not known: pass it as executeScript(body, bars, inputs, { tickerid }).');
2405
- }
2406
- return chartCtx.tickerid;
2528
+ return chartTickerid();
2529
+ },
2530
+ get main_tickerid() {
2531
+ const id = chartTickerid();
2532
+ return chartCtx.mainTickerid ?? id;
2533
+ },
2534
+ get ticker() {
2535
+ const id = chartTickerid();
2536
+ return chartCtx.ticker ?? splitTickerid(id)[1];
2537
+ },
2538
+ get prefix() {
2539
+ const id = chartTickerid();
2540
+ return chartCtx.prefix === undefined ? splitTickerid(id)[0] : (chartCtx.prefix ?? '');
2407
2541
  },
2408
2542
  get session() {
2409
2543
  collector();
@@ -2419,11 +2553,85 @@ export const syminfo = {
2419
2553
  return chartText('basecurrency', 'syminfo.basecurrency');
2420
2554
  },
2421
2555
  get root() {
2422
- return chartText('root', 'syminfo.root');
2556
+ if (chartCtx.root !== undefined)
2557
+ return chartText('root', 'syminfo.root');
2558
+ return tickerRoot(syminfo.ticker, chartCtx.symbolType);
2423
2559
  },
2424
2560
  get description() {
2425
2561
  return chartText('description', 'syminfo.description');
2426
2562
  },
2563
+ get country() {
2564
+ return chartText('country', 'syminfo.country');
2565
+ },
2566
+ get current_contract() {
2567
+ return chartText('currentContract', 'syminfo.current_contract');
2568
+ },
2569
+ get expiration_date() {
2570
+ return symbolNumber('expirationDate', 'syminfo.expiration_date');
2571
+ },
2572
+ get sector() {
2573
+ return chartText('sector', 'syminfo.sector');
2574
+ },
2575
+ get industry() {
2576
+ return chartText('industry', 'syminfo.industry');
2577
+ },
2578
+ get isin() {
2579
+ return chartText('isin', 'syminfo.isin');
2580
+ },
2581
+ get volumetype() {
2582
+ return chartText('volumetype', 'syminfo.volumetype');
2583
+ },
2584
+ get employees() {
2585
+ return symbolNumber('employees', 'syminfo.employees');
2586
+ },
2587
+ get shareholders() {
2588
+ return symbolNumber('shareholders', 'syminfo.shareholders');
2589
+ },
2590
+ get shares_outstanding_total() {
2591
+ return symbolNumber('sharesOutstandingTotal', 'syminfo.shares_outstanding_total');
2592
+ },
2593
+ get shares_outstanding_float() {
2594
+ return symbolNumber('sharesOutstandingFloat', 'syminfo.shares_outstanding_float');
2595
+ },
2596
+ get recommendations_buy() {
2597
+ return analystNumber('recommendations', 'buy', 'syminfo.recommendations_buy');
2598
+ },
2599
+ get recommendations_buy_strong() {
2600
+ return analystNumber('recommendations', 'buy_strong', 'syminfo.recommendations_buy_strong');
2601
+ },
2602
+ get recommendations_hold() {
2603
+ return analystNumber('recommendations', 'hold', 'syminfo.recommendations_hold');
2604
+ },
2605
+ get recommendations_sell() {
2606
+ return analystNumber('recommendations', 'sell', 'syminfo.recommendations_sell');
2607
+ },
2608
+ get recommendations_sell_strong() {
2609
+ return analystNumber('recommendations', 'sell_strong', 'syminfo.recommendations_sell_strong');
2610
+ },
2611
+ get recommendations_total() {
2612
+ return analystNumber('recommendations', 'total', 'syminfo.recommendations_total');
2613
+ },
2614
+ get recommendations_date() {
2615
+ return analystNumber('recommendations', 'date', 'syminfo.recommendations_date');
2616
+ },
2617
+ get target_price_average() {
2618
+ return analystNumber('targetPrice', 'average', 'syminfo.target_price_average');
2619
+ },
2620
+ get target_price_high() {
2621
+ return analystNumber('targetPrice', 'high', 'syminfo.target_price_high');
2622
+ },
2623
+ get target_price_low() {
2624
+ return analystNumber('targetPrice', 'low', 'syminfo.target_price_low');
2625
+ },
2626
+ get target_price_median() {
2627
+ return analystNumber('targetPrice', 'median', 'syminfo.target_price_median');
2628
+ },
2629
+ get target_price_estimates() {
2630
+ return analystNumber('targetPrice', 'estimates', 'syminfo.target_price_estimates');
2631
+ },
2632
+ get target_price_date() {
2633
+ return analystNumber('targetPrice', 'date', 'syminfo.target_price_date');
2634
+ },
2427
2635
  };
2428
2636
  function calendar(fn) {
2429
2637
  return ((time, timezone) => {
@@ -2776,25 +2984,12 @@ function runExternal(symbol, heikin, tf, expression, ignoreInvalid, own) {
2776
2984
  let result;
2777
2985
  let values;
2778
2986
  ctxBars.setAll(bars);
2779
- // the expression sees that symbol: its ticker, timeframe, calendar and properties
2780
- chartCtx = {
2781
- ...chartCtx,
2782
- tickerid: symbol,
2783
- timeframe: tf,
2784
- timezone: info.timezone,
2785
- session: info.session,
2786
- regularSession: info.regularSession,
2787
- mintick: info.mintick,
2788
- minmove: info.minmove,
2789
- pricescale: info.pricescale,
2790
- pointvalue: info.pointvalue,
2791
- mincontract: info.mincontract,
2792
- symbolType: info.symbolType,
2793
- currency: info.currency,
2794
- basecurrency: info.basecurrency,
2795
- root: info.root,
2796
- description: info.description,
2797
- };
2987
+ // the expression sees that symbol: its ticker, timeframe, calendar and properties (the chart's own symbol stays the
2988
+ // main one)
2989
+ const seen = { ...chartCtx, tickerid: symbol, timeframe: tf, mainTickerid: chartCtx.mainTickerid ?? chartCtx.tickerid };
2990
+ for (const key of SYMBOL_INFO_KEYS)
2991
+ seen[key] = info[key];
2992
+ chartCtx = seen;
2798
2993
  try {
2799
2994
  result = expression();
2800
2995
  const parts = Array.isArray(result) ? result : [result];
@@ -2898,7 +3093,155 @@ function seedCall(...args) {
2898
3093
  unsupportedSecurityArgs('request.seed', undefined, a[4]);
2899
3094
  return seed(a[0], a[1], a[2], a[3]);
2900
3095
  }
2901
- export const request = strictNamespace('request', { security: securityCall, security_lower_tf: securityLowerTfCall, seed: seedCall });
3096
+ // ── request.dividends / request.splits / request.earnings (#211) ─────────────
3097
+ /** The events of `ticker` ("" or the chart's: the chart symbol); {} while the host has not given them (the run ends with
3098
+ * a MissingSymbolDataError). */
3099
+ function symbolEvents(ticker) {
3100
+ collector();
3101
+ const symbol = ticker === '' ? chartTickerid() : ticker;
3102
+ const events = chartCtx.events?.(symbol);
3103
+ if (events === undefined) {
3104
+ if (!missingSymbols.some((r) => r.events && r.symbol === symbol))
3105
+ missingSymbols.push({ symbol, timeframe: '', events: true });
3106
+ return {};
3107
+ }
3108
+ return events;
3109
+ }
3110
+ /** One value of each event; throws when no event has it (the host does not have it), na where one has none. */
3111
+ function eventField(list, field, name, ticker) {
3112
+ if (list.length && list.every((e) => e[field] === undefined)) {
3113
+ throw new Error(`${name}: the ${String(field)} values of ${ticker || 'the chart symbol'} are not known.`);
3114
+ }
3115
+ return list.map((e) => {
3116
+ const v = e[field];
3117
+ return typeof v === 'number' ? v : NaN;
3118
+ });
3119
+ }
3120
+ /** A Series of event values on the chart bars, placed by PineScript's rules (see `security/events`). */
3121
+ function eventSeries(times, values, gaps, lookahead) {
3122
+ incremental.nonIncremental('request.dividends / splits / earnings');
3123
+ const opens = ctxBars.bars.map(barTime);
3124
+ const tf = chartTimeframe().period;
3125
+ const span = timeframeCore.info(tf).isticks ? 0 : timeframeCore.in_seconds(tf) * 1000;
3126
+ const { bars } = sessionBars();
3127
+ // a bar without a session period closes where the next one opens
3128
+ const closes = opens.map((t, i) => {
3129
+ const c = bars.closeOf(t, tf);
3130
+ return Number.isFinite(c) ? c : (opens[i + 1] ?? t + span);
3131
+ });
3132
+ const order = times.map((_, i) => i).sort((a, b) => times[a] - times[b]);
3133
+ const events = order.map((i) => ({ time: times[i], value: values[i] }));
3134
+ return Series.fromArray(ctxBars, eventsOnBars(opens, closes, tf, events, { gaps: gaps === barmerge.gaps_on, lookahead: lookahead === barmerge.lookahead_on }));
3135
+ }
3136
+ /** PineScript `dividends.*`: the fields of `request.dividends` and the next announced dividend of the chart symbol. */
3137
+ export const dividends = {
3138
+ net: 'net',
3139
+ gross: 'gross',
3140
+ /** Amount of the next dividend (net), na when none is announced */
3141
+ get future_amount() {
3142
+ return nextDividend()?.net ?? NaN;
3143
+ },
3144
+ /** Ex-date of the next dividend (ms) */
3145
+ get future_ex_date() {
3146
+ return nextDividend()?.time ?? NaN;
3147
+ },
3148
+ /** Payment date of the next dividend (ms) */
3149
+ get future_pay_date() {
3150
+ return nextDividend()?.payDate ?? NaN;
3151
+ },
3152
+ };
3153
+ /** PineScript `splits.*`: the fields of `request.splits`. */
3154
+ export const splits = { numerator: 'numerator', denominator: 'denominator' };
3155
+ /** PineScript `earnings.*`: the fields of `request.earnings` and the next earnings release of the chart symbol. */
3156
+ export const earnings = {
3157
+ actual: 'actual',
3158
+ estimate: 'estimate',
3159
+ standardized: 'standardized',
3160
+ /** Estimated earnings per share of the next release */
3161
+ get future_eps() {
3162
+ return nextEarnings()?.estimate ?? NaN;
3163
+ },
3164
+ /** Estimated revenue of the next release */
3165
+ get future_revenue() {
3166
+ return nextEarnings()?.revenueEstimate ?? NaN;
3167
+ },
3168
+ /** Time of the next release (ms) */
3169
+ get future_time() {
3170
+ return nextEarnings()?.time ?? NaN;
3171
+ },
3172
+ /** End of the fiscal period of the next release (ms) */
3173
+ get future_period_end_time() {
3174
+ return nextEarnings()?.periodEnd ?? NaN;
3175
+ },
3176
+ };
3177
+ /** The first event after the current time of the run in the chart symbol's list, when the host gives the announced ones. */
3178
+ function nextEvent(kind) {
3179
+ const events = symbolEvents('');
3180
+ if (!Object.keys(events).length)
3181
+ return undefined;
3182
+ if (!events.future?.[kind])
3183
+ throw new Error(`${kind}.future_*: the announced ${kind} of ${chartTickerid()} are not known.`);
3184
+ return events[kind]?.find((e) => e.time > runNow);
3185
+ }
3186
+ const nextDividend = () => nextEvent('dividends');
3187
+ const nextEarnings = () => nextEvent('earnings');
3188
+ const DIVIDENDS_PARAMETERS = ['ticker', 'field', 'gaps', 'lookahead', 'ignore_invalid_symbol', 'currency'];
3189
+ const SPLITS_PARAMETERS = ['ticker', 'field', 'gaps', 'lookahead', 'ignore_invalid_symbol'];
3190
+ /**
3191
+ * PineScript `request.dividends(ticker, field, gaps, lookahead, ignore_invalid_symbol, currency)`: the dividend per
3192
+ * share (`dividends.net`, default, or `dividends.gross`) as declared, from the bar after its ex-date's day (see
3193
+ * `security/events`). na before the first dividend. The events come from `ChartContext.events`.
3194
+ */
3195
+ function dividendsCall(...args) {
3196
+ const a = namedArguments('request.dividends', DIVIDENDS_PARAMETERS, args);
3197
+ unsupportedSecurityArgs('request.dividends', a[5], undefined);
3198
+ const ticker = a[0] ?? '';
3199
+ const field = a[1] ?? dividends.net;
3200
+ if (field !== dividends.net && field !== dividends.gross)
3201
+ throw new Error(`request.dividends(): unknown field "${field}": dividends.net or dividends.gross.`);
3202
+ const list = symbolEvents(ticker).dividends ?? [];
3203
+ const values = field === dividends.gross ? list.map((d) => d.gross ?? d.net) : eventField(list, 'net', 'request.dividends', ticker);
3204
+ return eventSeries(list.map((d) => d.time), values, a[2], a[3]);
3205
+ }
3206
+ /**
3207
+ * PineScript `request.splits(ticker, field, gaps, lookahead, ignore_invalid_symbol)`: the numerator
3208
+ * (`splits.numerator`) or the denominator (`splits.denominator`) of the last split, from the bar after its day.
3209
+ */
3210
+ function splitsCall(...args) {
3211
+ const a = namedArguments('request.splits', SPLITS_PARAMETERS, args);
3212
+ const ticker = a[0] ?? '';
3213
+ const field = a[1];
3214
+ if (field !== splits.numerator && field !== splits.denominator) {
3215
+ throw new Error('request.splits(): the field is splits.numerator or splits.denominator.');
3216
+ }
3217
+ const list = symbolEvents(ticker).splits ?? [];
3218
+ return eventSeries(list.map((s) => s.time), eventField(list, field, 'request.splits', ticker), a[2], a[3]);
3219
+ }
3220
+ /**
3221
+ * PineScript `request.earnings(ticker, field, gaps, lookahead, ignore_invalid_symbol, currency)`: earnings per share of
3222
+ * the last release (`earnings.actual`, default, `earnings.estimate` or `earnings.standardized`), from the bar after the
3223
+ * period of the chart timeframe it was published in (the next day on a daily chart).
3224
+ */
3225
+ function earningsCall(...args) {
3226
+ const a = namedArguments('request.earnings', DIVIDENDS_PARAMETERS, args);
3227
+ unsupportedSecurityArgs('request.earnings', a[5], undefined);
3228
+ const ticker = a[0] ?? '';
3229
+ const field = a[1] ?? earnings.actual;
3230
+ if (field !== earnings.actual && field !== earnings.estimate && field !== earnings.standardized) {
3231
+ throw new Error(`request.earnings(): unknown field "${field}": earnings.actual, earnings.estimate or earnings.standardized.`);
3232
+ }
3233
+ // announced releases still to come have no values yet
3234
+ const list = (symbolEvents(ticker).earnings ?? []).filter((e) => e.time <= runNow);
3235
+ return eventSeries(list.map((e) => e.time), eventField(list, field, 'request.earnings', ticker), a[2], a[3]);
3236
+ }
3237
+ export const request = strictNamespace('request', {
3238
+ security: securityCall,
3239
+ security_lower_tf: securityLowerTfCall,
3240
+ seed: seedCall,
3241
+ dividends: dividendsCall,
3242
+ splits: splitsCall,
3243
+ earnings: earningsCall,
3244
+ });
2902
3245
  const loopBar = () => currentBar;
2903
3246
  /** Wraps a drawing namespace and keeps its `all` getter (the live drawings in creation order). */
2904
3247
  function drawings(name, members, all) {