oakscriptjs 0.21.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oakscriptjs",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "type": "module",
5
5
  "description": "PineScript v6 compatible technical analysis library for JavaScript/TypeScript",
6
6
  "main": "./dist/cjs/index.js",
@@ -41,8 +41,8 @@ Every kind takes an options object after the title. `...common` stands for the o
41
41
 
42
42
  | Call | Returns |
43
43
  |---|---|
44
- | `input.int(defval, title, { minval, maxval, step, ...common })` | integer (rounded) |
45
- | `input.float(defval, title, { minval, maxval, step, ...common })` | number |
44
+ | `input.int(defval, title, { minval, maxval, step, options: [...], ...common })` | integer (rounded; a choice list with `options`) |
45
+ | `input.float(defval, title, { minval, maxval, step, options: [...], ...common })` | number (a choice list with `options`) |
46
46
  | `input.price(defval, title, { ...common })` | number (a price level) |
47
47
  | `input.bool(defval, title, { ...common })` | boolean |
48
48
  | `input.string(defval, title, { options: [...], ...common })` | string (a choice list with `options`) |
@@ -53,6 +53,7 @@ Every kind takes an options object after the title. `...common` stands for the o
53
53
  | `input.session("0930-1600", title, { options, ...common })` | session string |
54
54
  | `input.symbol("NASDAQ:AAPL", title, { options, ...common })` | ticker id for `request.security` |
55
55
  | `input.time(timestamp("2024-01-01"), title, { ...common })` | UNIX time in ms |
56
+ | `input.enum(MaType.sma, title, { options: [...], ...common })` | a field of an enum made with `defineEnum()` (a choice list of its titles; `options`: some of its fields) |
56
57
 
57
58
  The common options, as in Pine:
58
59
 
@@ -79,6 +80,15 @@ const src = mode === "HL2" ? hl2 : close; // inputs are plain values: JS operato
79
80
  plot(ta.sma(src, maLength), "MA", { color: maColor, display: showMa ? "all" : "none" });
80
81
  ```
81
82
 
83
+ Pine's `enum` is `defineEnum({ field: "Title", ... })` (an empty title is the field name). Fields compare with
84
+ `===`, `String(field)` and `str.tostring(field)` give the title, `field.name` the name:
85
+
86
+ ```js
87
+ const MaType = defineEnum({ sma: "Simple", ema: "Exponential" });
88
+ const maType = input.enum(MaType.sma, "Average");
89
+ const ma = maType === MaType.ema ? ta.ema(close, 20) : ta.sma(close, 20);
90
+ ```
91
+
82
92
  **Input ids.** The host sets inputs by id: the title in snake case (`"Fast length"` is `fast_length`, a repeated
83
93
  title gets `_2`, `_3`). Keep titles stable: renaming one resets the user's value.
84
94
 
@@ -40,7 +40,8 @@
40
40
  "timeframe",
41
41
  "session",
42
42
  "time",
43
- "symbol"
43
+ "symbol",
44
+ "enum"
44
45
  ],
45
46
  "description": "input type"
46
47
  },
package/src/check/spec.ts CHANGED
@@ -15,7 +15,7 @@ type Field =
15
15
 
16
16
  const num = (doc: string): Field => ({ kind: 'number', doc });
17
17
 
18
- export const INPUT_TYPES = ['int', 'float', 'bool', 'string', 'text_area', 'source', 'color', 'timeframe', 'session', 'time', 'symbol'] as const;
18
+ export const INPUT_TYPES = ['int', 'float', 'bool', 'string', 'text_area', 'source', 'color', 'timeframe', 'session', 'time', 'symbol', 'enum'] as const;
19
19
  export const OUTPUT_KINDS = ['plot', 'shape', 'char', 'arrow', 'candle', 'bar', 'hline', 'bgcolor', 'barcolor', 'alertcondition'] as const;
20
20
 
21
21
  /** The keys of a spec checked by checkScript. */
@@ -71,9 +71,9 @@ export interface InputConfig {
71
71
  /**
72
72
  * Type of input. `timeframe` and `session` values are strings ("60", "1D", "0930-1600:23456";
73
73
  * an empty timeframe means the chart timeframe), `time` values are UNIX times in milliseconds. A `text_area`
74
- * value is a string that can hold several lines.
74
+ * value is a string that can hold several lines. An `enum` value is the field name of one of its `options`.
75
75
  */
76
- type: 'int' | 'float' | 'bool' | 'string' | 'text_area' | 'source' | 'color' | 'timeframe' | 'session' | 'time' | 'symbol';
76
+ type: 'int' | 'float' | 'bool' | 'string' | 'text_area' | 'source' | 'color' | 'timeframe' | 'session' | 'time' | 'symbol' | 'enum';
77
77
  /** Default value */
78
78
  defval: unknown;
79
79
  /** Display title */
@@ -84,8 +84,13 @@ export interface InputConfig {
84
84
  max?: number;
85
85
  /** Step size (for numeric inputs) */
86
86
  step?: number;
87
- /** Options for dropdown selection (for string, timeframe and session inputs) */
88
- options?: string[];
87
+ /**
88
+ * Options for dropdown selection: strings (string, timeframe, session and symbol inputs), numbers (int and float
89
+ * inputs) or the field names of an enum input
90
+ */
91
+ options?: (string | number)[];
92
+ /** Titles of the options of an enum input, by field name */
93
+ optionsTitles?: Record<string, string>;
89
94
  /** Settings group header (PineScript `group`) */
90
95
  group?: string;
91
96
  /** Inputs with the same `inline` id are shown on one line (PineScript `inline`) */
@@ -50,6 +50,7 @@ declare global {
50
50
  const holdDrawing: typeof S.holdDrawing;
51
51
  const releaseDrawing: typeof S.releaseDrawing;
52
52
  const varDrawing: typeof S.varDrawing;
53
+ const defineEnum: typeof S.defineEnum;
53
54
  const StrategyRecorder: typeof S.StrategyRecorder;
54
55
  const input: typeof S.input;
55
56
  const open: typeof S.open;
@@ -1207,6 +1207,55 @@ export interface NumericInputOptions extends InputOptions {
1207
1207
  minval?: number;
1208
1208
  maxval?: number;
1209
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 };
1210
1259
  }
1211
1260
 
1212
1261
  export interface StringInputOptions extends InputOptions {
@@ -1238,7 +1287,7 @@ function registerInput<T>(config: Omit<InputConfig, 'id'>, fallbackId: string):
1238
1287
 
1239
1288
  function registerNumeric(type: 'int' | 'float', defval: number, title?: string, opts: NumericInputOptions = {}): number {
1240
1289
  const v = registerInput<unknown>(
1241
- { 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) },
1242
1291
  `input_${type}`
1243
1292
  );
1244
1293
  return typeof v === 'number' ? v : defval;
@@ -1250,8 +1299,9 @@ type InputArgs<O, D> = O & { title?: string; defval?: D };
1250
1299
  const COMMON_INPUT_KEYS = ['tooltip', 'inline', 'group', 'confirm', 'display', 'active'] as const;
1251
1300
  /** The PineScript arguments of each input kind (named arguments are checked against them). */
1252
1301
  const INPUT_KEYS: Record<string, readonly string[]> = {
1253
- int: ['defval', 'title', 'minval', 'maxval', 'step', ...COMMON_INPUT_KEYS],
1254
- 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],
1255
1305
  price: ['defval', 'title', ...COMMON_INPUT_KEYS],
1256
1306
  bool: ['defval', 'title', ...COMMON_INPUT_KEYS],
1257
1307
  string: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],
@@ -1363,6 +1413,32 @@ export const input = strictNamespace('input', {
1363
1413
  const a = inputArgs<number, InputOptions>('price', defval, title, opts);
1364
1414
  return registerNumeric('float', a.defval, a.title, a.opts);
1365
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
+ },
1366
1442
  /** Date and time as a UNIX time in milliseconds, e.g. `input.time(timestamp('2024-01-01'), 'Start')`. */
1367
1443
  time(defval: number | InputArgs<InputOptions, number>, title?: string | InputArgs<InputOptions, number>, opts?: InputOptions): number {
1368
1444
  const a = inputArgs<number, InputOptions>('time', defval, title, opts);