oakscriptjs 0.20.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/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/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 +211 -11
- package/dist/cjs/script/index.d.ts.map +1 -1
- package/dist/cjs/script/index.js +295 -29
- 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/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 +211 -11
- package/dist/esm/script/index.d.ts.map +1 -1
- package/dist/esm/script/index.js +314 -35
- 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/timeframes-symbols.md +27 -0
- package/src/check/harness.ts +27 -0
- package/src/script/globals.ts +3 -0
- package/src/script/index.ts +502 -43
- 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();
|
|
@@ -1736,12 +1744,13 @@ export function fixnan(source: Series | Array<string | undefined>): Series | Arr
|
|
|
1736
1744
|
}
|
|
1737
1745
|
|
|
1738
1746
|
/** 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.
|
|
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). */
|
|
1740
1749
|
export function na(x: Series): Series;
|
|
1741
1750
|
export function na(x: unknown): boolean;
|
|
1742
1751
|
export function na(x: unknown): Series | boolean {
|
|
1743
1752
|
if (x instanceof Series) return Series.fromArray(ctxBars, x.toArray().map((v) => (isNA(v) ? 1 : 0)));
|
|
1744
|
-
return isNA(x);
|
|
1753
|
+
return x === '' || isNA(x);
|
|
1745
1754
|
}
|
|
1746
1755
|
|
|
1747
1756
|
/** PineScript `nz(source, replacement)`; replacement defaults to 0. On a Series: each na value (NaN or +/-Infinity)
|
|
@@ -3122,13 +3131,54 @@ export interface ChartContext {
|
|
|
3122
3131
|
currency?: string;
|
|
3123
3132
|
/**
|
|
3124
3133
|
* 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)
|
|
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).
|
|
3126
3138
|
*/
|
|
3127
|
-
basecurrency?: string;
|
|
3128
|
-
/**
|
|
3129
|
-
|
|
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").
|
|
3144
|
+
*/
|
|
3145
|
+
root?: string | null;
|
|
3130
3146
|
/** Description of the symbol (PineScript `syminfo.description`): "Apple Inc." for NASDAQ:AAPL, "Bitcoin / U.S. dollar" for BITSTAMP:BTCUSD (#184) */
|
|
3131
|
-
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;
|
|
3132
3182
|
/** Chart foreground colour (PineScript `chart.fg_color`), e.g. "#DBDBDB" on a dark chart */
|
|
3133
3183
|
foregroundColor?: string;
|
|
3134
3184
|
/** Chart background colour (PineScript `chart.bg_color`), e.g. "#0F0F0F" on a dark chart */
|
|
@@ -3188,12 +3238,108 @@ export type SymbolInfo = Pick<
|
|
|
3188
3238
|
| 'basecurrency'
|
|
3189
3239
|
| 'root'
|
|
3190
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'
|
|
3191
3256
|
>;
|
|
3192
3257
|
|
|
3193
|
-
/**
|
|
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
|
+
*/
|
|
3194
3339
|
export interface SymbolDataRequest {
|
|
3195
3340
|
symbol: string;
|
|
3196
3341
|
timeframe: string;
|
|
3342
|
+
events?: boolean;
|
|
3197
3343
|
}
|
|
3198
3344
|
|
|
3199
3345
|
/**
|
|
@@ -3202,9 +3348,13 @@ export interface SymbolDataRequest {
|
|
|
3202
3348
|
*/
|
|
3203
3349
|
export class MissingSymbolDataError extends Error {
|
|
3204
3350
|
constructor(readonly requests: SymbolDataRequest[]) {
|
|
3351
|
+
const bars = requests.filter((r) => !r.events);
|
|
3352
|
+
const events = requests.filter((r) => r.events);
|
|
3205
3353
|
super(
|
|
3206
|
-
|
|
3207
|
-
'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(' ')
|
|
3208
3358
|
);
|
|
3209
3359
|
this.name = 'MissingSymbolDataError';
|
|
3210
3360
|
}
|
|
@@ -3293,9 +3443,23 @@ function symbolProperty(key: 'mintick' | 'pointvalue' | 'mincontract'): number {
|
|
|
3293
3443
|
return value;
|
|
3294
3444
|
}
|
|
3295
3445
|
|
|
3296
|
-
/** 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 "". */
|
|
3297
3447
|
function chartText(
|
|
3298
|
-
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',
|
|
3299
3463
|
name: string
|
|
3300
3464
|
): string {
|
|
3301
3465
|
collector();
|
|
@@ -3303,7 +3467,61 @@ function chartText(
|
|
|
3303
3467
|
if (value === undefined) {
|
|
3304
3468
|
throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);
|
|
3305
3469
|
}
|
|
3306
|
-
|
|
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;
|
|
3307
3525
|
}
|
|
3308
3526
|
|
|
3309
3527
|
/** A visible range value: the chart context's, else the time of bar `index` (NaN without bars). */
|
|
@@ -3329,9 +3547,8 @@ function symbolScale(): [number, number] {
|
|
|
3329
3547
|
}
|
|
3330
3548
|
|
|
3331
3549
|
/**
|
|
3332
|
-
* PineScript `syminfo
|
|
3333
|
-
*
|
|
3334
|
-
* `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.
|
|
3335
3552
|
*/
|
|
3336
3553
|
export const syminfo = {
|
|
3337
3554
|
get mintick(): number {
|
|
@@ -3353,11 +3570,19 @@ export const syminfo = {
|
|
|
3353
3570
|
return exchangeTimezone();
|
|
3354
3571
|
},
|
|
3355
3572
|
get tickerid(): string {
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
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 ?? '');
|
|
3361
3586
|
},
|
|
3362
3587
|
get session(): string {
|
|
3363
3588
|
collector();
|
|
@@ -3373,11 +3598,84 @@ export const syminfo = {
|
|
|
3373
3598
|
return chartText('basecurrency', 'syminfo.basecurrency');
|
|
3374
3599
|
},
|
|
3375
3600
|
get root(): string {
|
|
3376
|
-
return chartText('root', 'syminfo.root');
|
|
3601
|
+
if (chartCtx.root !== undefined) return chartText('root', 'syminfo.root');
|
|
3602
|
+
return tickerRoot(syminfo.ticker, chartCtx.symbolType);
|
|
3377
3603
|
},
|
|
3378
3604
|
get description(): string {
|
|
3379
3605
|
return chartText('description', 'syminfo.description');
|
|
3380
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
|
+
},
|
|
3381
3679
|
};
|
|
3382
3680
|
|
|
3383
3681
|
/** A calendar function: `(time, timezone?)` on a UNIX time or on a Series of times. */
|
|
@@ -3809,25 +4107,11 @@ function runExternal<T extends SecurityValue>(
|
|
|
3809
4107
|
let result: T;
|
|
3810
4108
|
let values: number[][];
|
|
3811
4109
|
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
|
-
};
|
|
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;
|
|
3831
4115
|
try {
|
|
3832
4116
|
result = expression();
|
|
3833
4117
|
const parts = Array.isArray(result) ? result : [result];
|
|
@@ -4004,7 +4288,182 @@ function seedCall<T extends SecurityValue>(
|
|
|
4004
4288
|
return seed(a[0] as string, a[1] as string, a[2] as () => T, a[3] as boolean | undefined);
|
|
4005
4289
|
}
|
|
4006
4290
|
|
|
4007
|
-
|
|
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
|
+
});
|
|
4008
4467
|
|
|
4009
4468
|
// ── Drawing objects ──────────────────────────────────────────────────────────
|
|
4010
4469
|
// The drawing namespaces come from this bundle so that they share the registry that
|