oakscriptjs 0.23.0 → 0.25.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/README.md +25 -1
- package/bin/oakscript.mjs +10 -3
- package/dist/cjs/box/index.d.ts +348 -289
- package/dist/cjs/box/index.d.ts.map +1 -1
- package/dist/cjs/box/index.js.map +2 -2
- package/dist/cjs/check/node.d.ts.map +1 -1
- package/dist/cjs/check/node.js +1 -0
- package/dist/cjs/check/node.js.map +2 -2
- package/dist/cjs/check/preview.d.ts +31 -0
- package/dist/cjs/check/preview.d.ts.map +1 -0
- package/dist/cjs/check/preview.js +303 -0
- package/dist/cjs/check/preview.js.map +7 -0
- package/dist/cjs/color/index.d.ts +11 -11
- package/dist/cjs/color/index.js.map +1 -1
- package/dist/cjs/color/parse.d.ts +2 -0
- package/dist/cjs/color/parse.d.ts.map +1 -1
- package/dist/cjs/color/parse.js +6 -0
- package/dist/cjs/color/parse.js.map +2 -2
- package/dist/cjs/compare/index.d.ts +76 -12
- package/dist/cjs/compare/index.d.ts.map +1 -1
- package/dist/cjs/compare/index.js.map +2 -2
- package/dist/cjs/drawing/registry.d.ts +28 -5
- package/dist/cjs/drawing/registry.d.ts.map +1 -1
- package/dist/cjs/drawing/registry.js +14 -0
- package/dist/cjs/drawing/registry.js.map +2 -2
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/label/index.d.ts +265 -187
- package/dist/cjs/label/index.d.ts.map +1 -1
- package/dist/cjs/label/index.js +1 -1
- package/dist/cjs/label/index.js.map +2 -2
- package/dist/cjs/line/index.d.ts +247 -207
- package/dist/cjs/line/index.d.ts.map +1 -1
- package/dist/cjs/line/index.js.map +2 -2
- package/dist/cjs/linefill/index.d.ts +61 -89
- package/dist/cjs/linefill/index.d.ts.map +1 -1
- package/dist/cjs/linefill/index.js.map +2 -2
- package/dist/cjs/math/index.d.ts +49 -40
- package/dist/cjs/math/index.d.ts.map +1 -1
- package/dist/cjs/math/index.js.map +2 -2
- package/dist/cjs/polyline/index.d.ts +57 -78
- package/dist/cjs/polyline/index.d.ts.map +1 -1
- package/dist/cjs/polyline/index.js.map +2 -2
- package/dist/cjs/runtime/input-active.d.ts +2 -2
- package/dist/cjs/runtime/input-active.js.map +1 -1
- package/dist/cjs/runtime/series.d.ts +241 -161
- package/dist/cjs/runtime/series.d.ts.map +1 -1
- package/dist/cjs/runtime/series.js +223 -127
- package/dist/cjs/runtime/series.js.map +2 -2
- package/dist/cjs/script/api/alert.d.ts +37 -0
- package/dist/cjs/script/api/alert.d.ts.map +1 -0
- package/dist/cjs/script/api/alert.js +17 -0
- package/dist/cjs/script/api/alert.js.map +7 -0
- package/dist/cjs/script/api/calc.d.ts +232 -0
- package/dist/cjs/script/api/calc.d.ts.map +1 -0
- package/dist/cjs/script/api/calc.js +17 -0
- package/dist/cjs/script/api/calc.js.map +7 -0
- package/dist/cjs/script/api/color.d.ts +213 -0
- package/dist/cjs/script/api/color.d.ts.map +1 -0
- package/dist/cjs/script/api/color.js +17 -0
- package/dist/cjs/script/api/color.js.map +7 -0
- package/dist/cjs/script/api/context.d.ts +764 -0
- package/dist/cjs/script/api/context.d.ts.map +1 -0
- package/dist/cjs/script/api/context.js +17 -0
- package/dist/cjs/script/api/context.js.map +7 -0
- package/dist/cjs/script/api/log.d.ts +58 -0
- package/dist/cjs/script/api/log.d.ts.map +1 -0
- package/dist/cjs/script/api/log.js +17 -0
- package/dist/cjs/script/api/log.js.map +7 -0
- package/dist/cjs/script/api/strategy.d.ts +391 -0
- package/dist/cjs/script/api/strategy.d.ts.map +1 -0
- package/dist/cjs/script/api/strategy.js +17 -0
- package/dist/cjs/script/api/strategy.js.map +7 -0
- package/dist/cjs/script/api/ta.d.ts +1012 -0
- package/dist/cjs/script/api/ta.d.ts.map +1 -0
- package/dist/cjs/script/api/ta.js +17 -0
- package/dist/cjs/script/api/ta.js.map +7 -0
- package/dist/cjs/script/api/table.d.ts +479 -0
- package/dist/cjs/script/api/table.d.ts.map +1 -0
- package/dist/cjs/script/api/table.js +17 -0
- package/dist/cjs/script/api/table.js.map +7 -0
- package/dist/cjs/script/constants.d.ts +228 -83
- package/dist/cjs/script/constants.d.ts.map +1 -1
- package/dist/cjs/script/constants.js +87 -0
- package/dist/cjs/script/constants.js.map +2 -2
- package/dist/cjs/script/define.d.ts +94 -0
- package/dist/cjs/script/define.d.ts.map +1 -0
- package/dist/cjs/script/define.js +127 -0
- package/dist/cjs/script/define.js.map +7 -0
- package/dist/cjs/script/drawing-args.d.ts.map +1 -1
- package/dist/cjs/script/drawing-args.js +1 -1
- package/dist/cjs/script/drawing-args.js.map +2 -2
- package/dist/cjs/script/formula.d.ts +53 -0
- package/dist/cjs/script/formula.d.ts.map +1 -0
- package/dist/cjs/script/formula.js +402 -0
- package/dist/cjs/script/formula.js.map +7 -0
- package/dist/cjs/script/globals.d.ts +10 -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 +1065 -1006
- package/dist/cjs/script/index.d.ts.map +1 -1
- package/dist/cjs/script/index.js +532 -61
- package/dist/cjs/script/index.js.map +3 -3
- package/dist/cjs/script/json.d.ts +117 -0
- package/dist/cjs/script/json.d.ts.map +1 -0
- package/dist/cjs/script/json.js +321 -0
- package/dist/cjs/script/json.js.map +7 -0
- package/dist/cjs/security/other.d.ts +8 -3
- package/dist/cjs/security/other.d.ts.map +1 -1
- package/dist/cjs/security/other.js +23 -6
- package/dist/cjs/security/other.js.map +2 -2
- package/dist/cjs/str/index.d.ts +50 -75
- package/dist/cjs/str/index.d.ts.map +1 -1
- package/dist/cjs/str/index.js +2 -2
- package/dist/cjs/str/index.js.map +2 -2
- package/dist/cjs/strategy/index.d.ts +102 -1
- package/dist/cjs/strategy/index.d.ts.map +1 -1
- package/dist/cjs/strategy/index.js.map +2 -2
- package/dist/cjs/table/index.d.ts +330 -49
- package/dist/cjs/table/index.d.ts.map +1 -1
- package/dist/cjs/table/index.js +55 -27
- package/dist/cjs/table/index.js.map +2 -2
- package/dist/cjs/text/index.d.ts +12 -14
- package/dist/cjs/text/index.d.ts.map +1 -1
- package/dist/cjs/text/index.js.map +2 -2
- package/dist/cjs/types/index.d.ts +15 -8
- package/dist/cjs/types/index.d.ts.map +1 -1
- package/dist/cjs/types/index.js +12 -3
- package/dist/cjs/types/index.js.map +2 -2
- package/dist/esm/box/index.d.ts +348 -289
- package/dist/esm/box/index.d.ts.map +1 -1
- package/dist/esm/box/index.js +276 -276
- package/dist/esm/box/index.js.map +1 -1
- package/dist/esm/check/node.d.ts.map +1 -1
- package/dist/esm/check/node.js +1 -0
- package/dist/esm/check/node.js.map +1 -1
- package/dist/esm/check/preview.d.ts +31 -0
- package/dist/esm/check/preview.d.ts.map +1 -0
- package/dist/esm/check/preview.js +296 -0
- package/dist/esm/check/preview.js.map +1 -0
- package/dist/esm/color/index.d.ts +11 -11
- package/dist/esm/color/index.js +11 -11
- package/dist/esm/color/parse.d.ts +2 -0
- package/dist/esm/color/parse.d.ts.map +1 -1
- package/dist/esm/color/parse.js +7 -0
- package/dist/esm/color/parse.js.map +1 -1
- package/dist/esm/compare/index.d.ts +76 -12
- package/dist/esm/compare/index.d.ts.map +1 -1
- package/dist/esm/compare/index.js +76 -12
- package/dist/esm/compare/index.js.map +1 -1
- package/dist/esm/drawing/registry.d.ts +28 -5
- package/dist/esm/drawing/registry.d.ts.map +1 -1
- package/dist/esm/drawing/registry.js +39 -3
- package/dist/esm/drawing/registry.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/label/index.d.ts +265 -187
- package/dist/esm/label/index.d.ts.map +1 -1
- package/dist/esm/label/index.js +207 -177
- package/dist/esm/label/index.js.map +1 -1
- package/dist/esm/line/index.d.ts +247 -207
- package/dist/esm/line/index.d.ts.map +1 -1
- package/dist/esm/line/index.js +202 -194
- package/dist/esm/line/index.js.map +1 -1
- package/dist/esm/linefill/index.d.ts +61 -89
- package/dist/esm/linefill/index.d.ts.map +1 -1
- package/dist/esm/linefill/index.js +61 -89
- package/dist/esm/linefill/index.js.map +1 -1
- package/dist/esm/math/index.d.ts +49 -40
- package/dist/esm/math/index.d.ts.map +1 -1
- package/dist/esm/math/index.js +22 -9
- package/dist/esm/math/index.js.map +1 -1
- package/dist/esm/polyline/index.d.ts +57 -78
- package/dist/esm/polyline/index.d.ts.map +1 -1
- package/dist/esm/polyline/index.js +57 -78
- package/dist/esm/polyline/index.js.map +1 -1
- package/dist/esm/runtime/input-active.d.ts +2 -2
- package/dist/esm/runtime/input-active.js +2 -2
- package/dist/esm/runtime/series.d.ts +241 -161
- package/dist/esm/runtime/series.d.ts.map +1 -1
- package/dist/esm/runtime/series.js +241 -161
- package/dist/esm/runtime/series.js.map +1 -1
- package/dist/esm/script/api/alert.d.ts +37 -0
- package/dist/esm/script/api/alert.d.ts.map +1 -0
- package/dist/esm/script/api/alert.js +7 -0
- package/dist/esm/script/api/alert.js.map +1 -0
- package/dist/esm/script/api/calc.d.ts +232 -0
- package/dist/esm/script/api/calc.d.ts.map +1 -0
- package/dist/esm/script/api/calc.js +6 -0
- package/dist/esm/script/api/calc.js.map +1 -0
- package/dist/esm/script/api/color.d.ts +213 -0
- package/dist/esm/script/api/color.d.ts.map +1 -0
- package/dist/esm/script/api/color.js +6 -0
- package/dist/esm/script/api/color.js.map +1 -0
- package/dist/esm/script/api/context.d.ts +764 -0
- package/dist/esm/script/api/context.d.ts.map +1 -0
- package/dist/esm/script/api/context.js +7 -0
- package/dist/esm/script/api/context.js.map +1 -0
- package/dist/esm/script/api/log.d.ts +58 -0
- package/dist/esm/script/api/log.d.ts.map +1 -0
- package/dist/esm/script/api/log.js +6 -0
- package/dist/esm/script/api/log.js.map +1 -0
- package/dist/esm/script/api/strategy.d.ts +391 -0
- package/dist/esm/script/api/strategy.d.ts.map +1 -0
- package/dist/esm/script/api/strategy.js +7 -0
- package/dist/esm/script/api/strategy.js.map +1 -0
- package/dist/esm/script/api/ta.d.ts +1012 -0
- package/dist/esm/script/api/ta.d.ts.map +1 -0
- package/dist/esm/script/api/ta.js +6 -0
- package/dist/esm/script/api/ta.js.map +1 -0
- package/dist/esm/script/api/table.d.ts +479 -0
- package/dist/esm/script/api/table.d.ts.map +1 -0
- package/dist/esm/script/api/table.js +7 -0
- package/dist/esm/script/api/table.js.map +1 -0
- package/dist/esm/script/constants.d.ts +228 -83
- package/dist/esm/script/constants.d.ts.map +1 -1
- package/dist/esm/script/constants.js +110 -24
- package/dist/esm/script/constants.js.map +1 -1
- package/dist/esm/script/define.d.ts +94 -0
- package/dist/esm/script/define.d.ts.map +1 -0
- package/dist/esm/script/define.js +136 -0
- package/dist/esm/script/define.js.map +1 -0
- package/dist/esm/script/drawing-args.d.ts.map +1 -1
- package/dist/esm/script/drawing-args.js +2 -1
- package/dist/esm/script/drawing-args.js.map +1 -1
- package/dist/esm/script/formula.d.ts +53 -0
- package/dist/esm/script/formula.d.ts.map +1 -0
- package/dist/esm/script/formula.js +408 -0
- package/dist/esm/script/formula.js.map +1 -0
- package/dist/esm/script/globals.d.ts +10 -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 +1065 -1006
- package/dist/esm/script/index.d.ts.map +1 -1
- package/dist/esm/script/index.js +1099 -153
- package/dist/esm/script/index.js.map +1 -1
- package/dist/esm/script/json.d.ts +117 -0
- package/dist/esm/script/json.d.ts.map +1 -0
- package/dist/esm/script/json.js +375 -0
- package/dist/esm/script/json.js.map +1 -0
- package/dist/esm/security/other.d.ts +8 -3
- package/dist/esm/security/other.d.ts.map +1 -1
- package/dist/esm/security/other.js +45 -10
- package/dist/esm/security/other.js.map +1 -1
- package/dist/esm/str/index.d.ts +50 -75
- package/dist/esm/str/index.d.ts.map +1 -1
- package/dist/esm/str/index.js +51 -76
- package/dist/esm/str/index.js.map +1 -1
- package/dist/esm/strategy/index.d.ts +102 -1
- package/dist/esm/strategy/index.d.ts.map +1 -1
- package/dist/esm/strategy/index.js +1 -1
- package/dist/esm/strategy/index.js.map +1 -1
- package/dist/esm/table/index.d.ts +330 -49
- package/dist/esm/table/index.d.ts.map +1 -1
- package/dist/esm/table/index.js +372 -61
- package/dist/esm/table/index.js.map +1 -1
- package/dist/esm/text/index.d.ts +12 -14
- package/dist/esm/text/index.d.ts.map +1 -1
- package/dist/esm/text/index.js +12 -14
- package/dist/esm/text/index.js.map +1 -1
- package/dist/esm/types/index.d.ts +15 -8
- package/dist/esm/types/index.d.ts.map +1 -1
- package/dist/esm/types/index.js +15 -8
- package/dist/esm/types/index.js.map +1 -1
- package/docs/first-indicator.md +152 -0
- package/docs/guide.md +1185 -0
- package/docs/inventory.md +772 -0
- package/docs/no-code.md +207 -0
- package/docs/recipes.md +202 -0
- package/package.json +2 -1
- package/skills/oakscript/SKILL.md +8 -0
- package/skills/oakscript/reference/errors.md +3 -2
- package/skills/oakscript/reference/timeframes-symbols.md +4 -0
- package/src/box/index.ts +348 -289
- package/src/check/node.ts +1 -0
- package/src/check/preview.ts +307 -0
- package/src/color/index.ts +11 -11
- package/src/color/parse.ts +7 -0
- package/src/compare/index.ts +76 -12
- package/src/drawing/registry.ts +44 -5
- package/src/index.ts +1 -1
- package/src/label/index.ts +267 -189
- package/src/line/index.ts +248 -208
- package/src/linefill/index.ts +61 -89
- package/src/math/index.ts +51 -42
- package/src/polyline/index.ts +57 -78
- package/src/runtime/input-active.ts +2 -2
- package/src/runtime/series.ts +243 -163
- package/src/script/api/alert.ts +43 -0
- package/src/script/api/calc.ts +250 -0
- package/src/script/api/color.ts +245 -0
- package/src/script/api/context.ts +944 -0
- package/src/script/api/log.ts +60 -0
- package/src/script/api/strategy.ts +410 -0
- package/src/script/api/ta.ts +1115 -0
- package/src/script/api/table.ts +538 -0
- package/src/script/constants.ts +229 -25
- package/src/script/define.ts +221 -0
- package/src/script/drawing-args.ts +2 -1
- package/src/script/formula.ts +438 -0
- package/src/script/globals.ts +10 -0
- package/src/script/index.ts +1520 -241
- package/src/script/json.ts +457 -0
- package/src/security/other.ts +43 -9
- package/src/str/index.ts +51 -76
- package/src/strategy/index.ts +102 -1
- package/src/table/index.ts +388 -62
- package/src/text/index.ts +12 -14
- package/src/types/index.ts +15 -8
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { type DefineIndicatorOptions, type IndicatorDefinition } from './define.js';
|
|
2
|
+
/** A setting: its default value alone (`14`, `true`, `"EMA"`), or the default with its details. */
|
|
3
|
+
export type JsonInput = number | boolean | string | {
|
|
4
|
+
default: number | boolean | string;
|
|
5
|
+
title?: string;
|
|
6
|
+
/** 'int', 'float', 'bool', 'text', 'source' (a price: "close", "hl2"...) or 'color'; default: from the default value. */
|
|
7
|
+
type?: 'int' | 'float' | 'bool' | 'text' | 'source' | 'color';
|
|
8
|
+
min?: number;
|
|
9
|
+
max?: number;
|
|
10
|
+
step?: number;
|
|
11
|
+
/** The values to choose from. */
|
|
12
|
+
options?: Array<string | number>;
|
|
13
|
+
tooltip?: string;
|
|
14
|
+
group?: string;
|
|
15
|
+
};
|
|
16
|
+
/** A colour: a name ("red", "teal"...), "#ff0000" or "rgba(255, 0, 0, 0.5)". */
|
|
17
|
+
export type JsonColor = string;
|
|
18
|
+
export interface JsonPlot {
|
|
19
|
+
title: string;
|
|
20
|
+
/** The formula of the line. */
|
|
21
|
+
value: string;
|
|
22
|
+
color?: JsonColor;
|
|
23
|
+
/** A colour where a formula is true, e.g. { "when": "value > value[1]", "color": "green", "else": "red" }. */
|
|
24
|
+
colorWhen?: {
|
|
25
|
+
when: string;
|
|
26
|
+
color: JsonColor;
|
|
27
|
+
else?: JsonColor;
|
|
28
|
+
};
|
|
29
|
+
width?: number;
|
|
30
|
+
style?: 'line' | 'histogram' | 'columns' | 'area' | 'circles' | 'stepline' | 'cross';
|
|
31
|
+
}
|
|
32
|
+
export interface JsonLevel {
|
|
33
|
+
title?: string;
|
|
34
|
+
value: number;
|
|
35
|
+
color?: JsonColor;
|
|
36
|
+
style?: 'solid' | 'dashed' | 'dotted';
|
|
37
|
+
}
|
|
38
|
+
export interface JsonFill {
|
|
39
|
+
/** The titles of two plots, or of two levels. */
|
|
40
|
+
between: [string, string];
|
|
41
|
+
color: JsonColor;
|
|
42
|
+
/** 0 (invisible) to 1 (solid); default 0.15. */
|
|
43
|
+
opacity?: number;
|
|
44
|
+
}
|
|
45
|
+
export interface JsonSignal {
|
|
46
|
+
title: string;
|
|
47
|
+
/** The formula of the condition. */
|
|
48
|
+
when: string;
|
|
49
|
+
shape?: 'triangleup' | 'triangledown' | 'arrowup' | 'arrowdown' | 'circle' | 'square' | 'diamond' | 'cross' | 'xcross' | 'flag' | 'labelup' | 'labeldown';
|
|
50
|
+
/** Where it is drawn: 'above' or 'below' the bar, at the 'top' or 'bottom' of the pane. */
|
|
51
|
+
position?: 'above' | 'below' | 'top' | 'bottom';
|
|
52
|
+
color?: JsonColor;
|
|
53
|
+
text?: string;
|
|
54
|
+
size?: 'tiny' | 'small' | 'normal' | 'large' | 'huge';
|
|
55
|
+
/** An alert an app can offer: true (the title as message) or the message. */
|
|
56
|
+
alert?: boolean | string;
|
|
57
|
+
}
|
|
58
|
+
export interface JsonColorRule {
|
|
59
|
+
title?: string;
|
|
60
|
+
when: string;
|
|
61
|
+
color: JsonColor;
|
|
62
|
+
/** 0 (invisible) to 1 (solid); default 1 for bar colours, 0.15 for backgrounds. */
|
|
63
|
+
opacity?: number;
|
|
64
|
+
}
|
|
65
|
+
/** An indicator in JSON. */
|
|
66
|
+
export interface IndicatorJson {
|
|
67
|
+
/** Optional, for editors: the JSON schema. */
|
|
68
|
+
$schema?: string;
|
|
69
|
+
title: string;
|
|
70
|
+
shortTitle?: string;
|
|
71
|
+
/** 'price' (on the price chart), 'separate' (its own pane) or 'auto' (default: chosen from the values). */
|
|
72
|
+
pane?: 'price' | 'separate' | 'auto';
|
|
73
|
+
/** The settings, by id: the names the formulas use and the names of the values given to `calculate`. */
|
|
74
|
+
inputs?: Record<string, JsonInput>;
|
|
75
|
+
/** Named calculations, in order: each formula can use the settings and the values before it. */
|
|
76
|
+
values?: Record<string, string>;
|
|
77
|
+
plots?: JsonPlot[];
|
|
78
|
+
levels?: JsonLevel[];
|
|
79
|
+
fills?: JsonFill[];
|
|
80
|
+
signals?: JsonSignal[];
|
|
81
|
+
background?: JsonColorRule[];
|
|
82
|
+
barColors?: JsonColorRule[];
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Host-side: the mistakes of an indicator in JSON, one message each ("plots[1]: "value" is missing."); empty when
|
|
86
|
+
* there are none. The formulas are checked when the indicator runs. A script does not call it.
|
|
87
|
+
* @param spec - The indicator in JSON, as parsed (an object).
|
|
88
|
+
* @returns One message per mistake.
|
|
89
|
+
*/
|
|
90
|
+
export declare function checkIndicatorJson(spec: unknown): string[];
|
|
91
|
+
/**
|
|
92
|
+
* Host-side: the script body of an indicator in JSON (for `executeScript`, or a host's own runner). A script does not
|
|
93
|
+
* call it.
|
|
94
|
+
* @param spec - The indicator in JSON: an object, or its text.
|
|
95
|
+
* @returns The script body. Throws on a mistake in the JSON.
|
|
96
|
+
*/
|
|
97
|
+
export declare function indicatorBodyFromJson(spec: IndicatorJson | string): () => void;
|
|
98
|
+
/**
|
|
99
|
+
* Host-side: an indicator described in JSON (an object or its text), ready to use: the same as `defineIndicator` of
|
|
100
|
+
* its script. A script does not call it.
|
|
101
|
+
*
|
|
102
|
+
* ```js
|
|
103
|
+
* const cross = defineIndicatorFromJson({
|
|
104
|
+
* title: 'Average cross',
|
|
105
|
+
* inputs: { fast: 9, slow: 21 },
|
|
106
|
+
* values: { fastLine: 'ema(close, fast)', slowLine: 'ema(close, slow)' },
|
|
107
|
+
* plots: [{ title: 'Fast', value: 'fastLine', color: 'teal' }, { title: 'Slow', value: 'slowLine', color: 'orange' }],
|
|
108
|
+
* signals: [{ title: 'Buy', when: 'crossover(fastLine, slowLine)', position: 'below', color: 'green', alert: true }],
|
|
109
|
+
* });
|
|
110
|
+
* cross.calculate(bars, { fast: 5 });
|
|
111
|
+
* ```
|
|
112
|
+
* @param spec - The indicator in JSON: an object, or its text.
|
|
113
|
+
* @param options - Strict mode and the other run options. Default: `{}`.
|
|
114
|
+
* @returns The indicator, as `defineIndicator` gives it. Throws on a mistake in the JSON.
|
|
115
|
+
*/
|
|
116
|
+
export declare function defineIndicatorFromJson(spec: IndicatorJson | string, options?: DefineIndicatorOptions): IndicatorDefinition;
|
|
117
|
+
//# sourceMappingURL=json.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"json.d.ts","sourceRoot":"","sources":["../../../src/script/json.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAmB,KAAK,sBAAsB,EAAE,KAAK,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAErG,mGAAmG;AACnG,MAAM,MAAM,SAAS,GACjB,MAAM,GACN,OAAO,GACP,MAAM,GACN;IACE,OAAO,EAAE,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;IACnC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,yHAAyH;IACzH,IAAI,CAAC,EAAE,KAAK,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,QAAQ,GAAG,OAAO,CAAC;IAC9D,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,iCAAiC;IACjC,OAAO,CAAC,EAAE,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC;IACjC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEN,gFAAgF;AAChF,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC;AAE/B,MAAM,WAAW,QAAQ;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,+BAA+B;IAC/B,KAAK,EAA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/H"}
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var json_exports = {};
|
|
20
|
+
__export(json_exports, {
|
|
21
|
+
checkIndicatorJson: () => checkIndicatorJson,
|
|
22
|
+
defineIndicatorFromJson: () => defineIndicatorFromJson,
|
|
23
|
+
indicatorBodyFromJson: () => indicatorBodyFromJson
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(json_exports);
|
|
26
|
+
var import_series = require("../runtime/series.js");
|
|
27
|
+
var import_parse = require("../color/parse.js");
|
|
28
|
+
var import_index = require("./index.js");
|
|
29
|
+
var import_formula = require("./formula.js");
|
|
30
|
+
var import_define = require("./define.js");
|
|
31
|
+
const KEYS = {
|
|
32
|
+
indicator: ["$schema", "title", "shortTitle", "pane", "inputs", "values", "plots", "levels", "fills", "signals", "background", "barColors"],
|
|
33
|
+
input: ["default", "title", "type", "min", "max", "step", "options", "tooltip", "group"],
|
|
34
|
+
plot: ["title", "value", "color", "colorWhen", "width", "style"],
|
|
35
|
+
colorWhen: ["when", "color", "else"],
|
|
36
|
+
level: ["title", "value", "color", "style"],
|
|
37
|
+
fill: ["between", "color", "opacity"],
|
|
38
|
+
signal: ["title", "when", "shape", "position", "color", "text", "size", "alert"],
|
|
39
|
+
rule: ["title", "when", "color", "opacity"]
|
|
40
|
+
};
|
|
41
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
42
|
+
function closest(name, names) {
|
|
43
|
+
const n = name.toLowerCase();
|
|
44
|
+
let best;
|
|
45
|
+
let bestD = Infinity;
|
|
46
|
+
for (const k of names) {
|
|
47
|
+
const a = n;
|
|
48
|
+
const b = k.toLowerCase();
|
|
49
|
+
const row = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
50
|
+
for (let i = 1; i <= a.length; i++) {
|
|
51
|
+
let diag = row[0];
|
|
52
|
+
row[0] = i;
|
|
53
|
+
for (let j = 1; j <= b.length; j++) {
|
|
54
|
+
const up = row[j];
|
|
55
|
+
row[j] = Math.min(up + 1, row[j - 1] + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
56
|
+
diag = up;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (row[b.length] < bestD) {
|
|
60
|
+
bestD = row[b.length];
|
|
61
|
+
best = k;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (bestD <= Math.max(2, Math.floor(name.length / 3))) return best;
|
|
65
|
+
return names.find((k) => k.length >= 3 && (n.startsWith(k.toLowerCase()) || k.toLowerCase().startsWith(n)));
|
|
66
|
+
}
|
|
67
|
+
class Checker {
|
|
68
|
+
errors = [];
|
|
69
|
+
error(where, msg) {
|
|
70
|
+
this.errors.push(`${where}: ${msg}`);
|
|
71
|
+
}
|
|
72
|
+
keys(where, o, kind, required = []) {
|
|
73
|
+
for (const k of Object.keys(o)) {
|
|
74
|
+
if (KEYS[kind].includes(k)) continue;
|
|
75
|
+
const near = closest(k, KEYS[kind]);
|
|
76
|
+
this.error(where, `there is no field "${k}".` + (near ? ` Did you mean "${near}"?` : "") + ` The fields are: ${KEYS[kind].join(", ")}.`);
|
|
77
|
+
}
|
|
78
|
+
for (const k of required) if (o[k] === void 0) this.error(where, `"${k}" is missing.`);
|
|
79
|
+
}
|
|
80
|
+
text(where, v, name) {
|
|
81
|
+
if (v !== void 0 && (typeof v !== "string" || !v.trim())) this.error(where, `"${name}" is a text.`);
|
|
82
|
+
}
|
|
83
|
+
oneOf(where, v, name, list) {
|
|
84
|
+
if (v !== void 0 && !list.includes(v)) this.error(where, `"${name}" is one of ${list.map((x) => `"${x}"`).join(", ")}, got ${JSON.stringify(v)}.`);
|
|
85
|
+
}
|
|
86
|
+
color(where, v, name) {
|
|
87
|
+
if (v !== void 0 && colorOf(v) === void 0) {
|
|
88
|
+
this.error(where, `"${name}" ${JSON.stringify(v)} is not a colour: write a name (${COLOR_NAMES.join(", ")}), "#ff0000" or "rgba(255, 0, 0, 0.5)".`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
opacity(where, v) {
|
|
92
|
+
if (v !== void 0 && !(typeof v === "number" && v >= 0 && v <= 1)) this.error(where, `"opacity" is from 0 (invisible) to 1 (solid), got ${JSON.stringify(v)}.`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const COLOR_NAMES = ["aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "white", "yellow"];
|
|
96
|
+
const SHAPES = ["triangleup", "triangledown", "arrowup", "arrowdown", "circle", "square", "diamond", "cross", "xcross", "flag", "labelup", "labeldown"];
|
|
97
|
+
const POSITIONS = { above: "abovebar", below: "belowbar", top: "top", bottom: "bottom" };
|
|
98
|
+
const STYLES = ["line", "histogram", "columns", "area", "circles", "stepline", "cross"];
|
|
99
|
+
const SOURCES = ["open", "high", "low", "close", "volume", "hl2", "hlc3", "ohlc4", "hlcc4"];
|
|
100
|
+
function colorOf(v) {
|
|
101
|
+
if (typeof v !== "string") return void 0;
|
|
102
|
+
const name = v.trim().toLowerCase();
|
|
103
|
+
if (COLOR_NAMES.includes(name)) return import_index.color[name];
|
|
104
|
+
return (0, import_parse.isColorText)(v) ? v.trim() : void 0;
|
|
105
|
+
}
|
|
106
|
+
function checkIndicatorJson(spec) {
|
|
107
|
+
const c = new Checker();
|
|
108
|
+
if (!isObject(spec)) return ['the indicator is a JSON object: { "title": "...", "plots": [...] }.'];
|
|
109
|
+
c.keys("indicator", spec, "indicator", ["title"]);
|
|
110
|
+
c.text("indicator", spec.title, "title");
|
|
111
|
+
c.text("indicator", spec.shortTitle, "shortTitle");
|
|
112
|
+
c.oneOf("indicator", spec.pane, "pane", ["price", "separate", "auto"]);
|
|
113
|
+
const names = /* @__PURE__ */ new Set();
|
|
114
|
+
const name = (where, id) => {
|
|
115
|
+
if (!/^[A-Za-z_]\w*$/.test(id)) c.error(where, `the name "${id}" has letters, digits and _ only, and does not start with a digit.`);
|
|
116
|
+
if (names.has(id)) c.error(where, `the name "${id}" is used twice.`);
|
|
117
|
+
names.add(id);
|
|
118
|
+
};
|
|
119
|
+
if (spec.inputs !== void 0) {
|
|
120
|
+
if (!isObject(spec.inputs)) c.error("inputs", 'the settings are an object: { "length": 14 }.');
|
|
121
|
+
else
|
|
122
|
+
for (const [id, v] of Object.entries(spec.inputs)) {
|
|
123
|
+
const where = `inputs.${id}`;
|
|
124
|
+
name(where, id);
|
|
125
|
+
if (isObject(v)) {
|
|
126
|
+
c.keys(where, v, "input", ["default"]);
|
|
127
|
+
c.oneOf(where, v.type, "type", ["int", "float", "bool", "text", "source", "color"]);
|
|
128
|
+
if (v.type === "source" && !SOURCES.includes(v.default)) c.error(where, `a source is one of ${SOURCES.join(", ")}.`);
|
|
129
|
+
if (v.type === "color") c.color(where, v.default, "default");
|
|
130
|
+
if (v.options !== void 0 && (!Array.isArray(v.options) || !v.options.includes(v.default))) c.error(where, '"options" is a list that holds the default.');
|
|
131
|
+
for (const k of ["min", "max", "step"]) if (v[k] !== void 0 && typeof v[k] !== "number") c.error(where, `"${k}" is a number.`);
|
|
132
|
+
} else if (!["number", "boolean", "string"].includes(typeof v)) {
|
|
133
|
+
c.error(where, 'a setting is a number, true / false, a text, or { "default": ..., "title": ... }.');
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (spec.values !== void 0) {
|
|
138
|
+
if (!isObject(spec.values)) c.error("values", 'the values are an object of formulas: { "fast": "ema(close, 9)" }.');
|
|
139
|
+
else
|
|
140
|
+
for (const [id, f] of Object.entries(spec.values)) {
|
|
141
|
+
name(`values.${id}`, id);
|
|
142
|
+
c.text(`values.${id}`, f, "formula");
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const list = (key, check) => {
|
|
146
|
+
const v = spec[key];
|
|
147
|
+
if (v === void 0) return;
|
|
148
|
+
if (!Array.isArray(v)) return c.error(key, "is a list: [ { ... }, { ... } ].");
|
|
149
|
+
v.forEach((o, k) => isObject(o) ? check(`${key}[${k}]`, o) : c.error(`${key}[${k}]`, "is an object { ... }."));
|
|
150
|
+
};
|
|
151
|
+
list("plots", (w, o) => {
|
|
152
|
+
c.keys(w, o, "plot", ["title", "value"]);
|
|
153
|
+
c.text(w, o.title, "title");
|
|
154
|
+
c.text(w, o.value, "value");
|
|
155
|
+
c.color(w, o.color, "color");
|
|
156
|
+
c.oneOf(w, o.style, "style", STYLES);
|
|
157
|
+
if (o.width !== void 0 && !(typeof o.width === "number" && o.width >= 1 && o.width <= 4)) c.error(w, '"width" is 1 to 4.');
|
|
158
|
+
if (o.colorWhen !== void 0) {
|
|
159
|
+
if (!isObject(o.colorWhen)) c.error(w, '"colorWhen" is { "when": "...", "color": "...", "else": "..." }.');
|
|
160
|
+
else {
|
|
161
|
+
c.keys(`${w}.colorWhen`, o.colorWhen, "colorWhen", ["when", "color"]);
|
|
162
|
+
c.color(`${w}.colorWhen`, o.colorWhen.color, "color");
|
|
163
|
+
c.color(`${w}.colorWhen`, o.colorWhen.else, "else");
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
list("levels", (w, o) => {
|
|
168
|
+
c.keys(w, o, "level", ["value"]);
|
|
169
|
+
if (o.value !== void 0 && typeof o.value !== "number") c.error(w, '"value" is a number.');
|
|
170
|
+
c.color(w, o.color, "color");
|
|
171
|
+
c.oneOf(w, o.style, "style", ["solid", "dashed", "dotted"]);
|
|
172
|
+
});
|
|
173
|
+
list("fills", (w, o) => {
|
|
174
|
+
c.keys(w, o, "fill", ["between", "color"]);
|
|
175
|
+
if (o.between !== void 0 && !(Array.isArray(o.between) && o.between.length === 2 && o.between.every((x) => typeof x === "string"))) {
|
|
176
|
+
c.error(w, '"between" is the titles of two plots or two levels: ["Upper", "Lower"].');
|
|
177
|
+
}
|
|
178
|
+
c.color(w, o.color, "color");
|
|
179
|
+
c.opacity(w, o.opacity);
|
|
180
|
+
});
|
|
181
|
+
list("signals", (w, o) => {
|
|
182
|
+
c.keys(w, o, "signal", ["title", "when"]);
|
|
183
|
+
c.text(w, o.when, "when");
|
|
184
|
+
c.oneOf(w, o.shape, "shape", SHAPES);
|
|
185
|
+
c.oneOf(w, o.position, "position", Object.keys(POSITIONS));
|
|
186
|
+
c.oneOf(w, o.size, "size", ["tiny", "small", "normal", "large", "huge"]);
|
|
187
|
+
c.color(w, o.color, "color");
|
|
188
|
+
if (o.alert !== void 0 && typeof o.alert !== "boolean" && typeof o.alert !== "string") c.error(w, '"alert" is true or the alert message.');
|
|
189
|
+
});
|
|
190
|
+
for (const key of ["background", "barColors"]) {
|
|
191
|
+
list(key, (w, o) => {
|
|
192
|
+
c.keys(w, o, "rule", ["when", "color"]);
|
|
193
|
+
c.text(w, o.when, "when");
|
|
194
|
+
c.color(w, o.color, "color");
|
|
195
|
+
c.opacity(w, o.opacity);
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
return c.errors;
|
|
199
|
+
}
|
|
200
|
+
const faded = (c, opacity) => opacity >= 1 ? c : import_index.color.fade(c, 1 - opacity);
|
|
201
|
+
function declareInput(id, v) {
|
|
202
|
+
const o = isObject(v) ? v : { default: v };
|
|
203
|
+
const title = o.title ?? id;
|
|
204
|
+
const common = { id, ...o.tooltip ? { tooltip: o.tooltip } : {}, ...o.group ? { group: o.group } : {} };
|
|
205
|
+
const d = o.default;
|
|
206
|
+
const type = o.type ?? (typeof d === "boolean" ? "bool" : typeof d === "number" ? Number.isInteger(d) && !(o.step && !Number.isInteger(o.step)) ? "int" : "float" : "text");
|
|
207
|
+
const numeric = { ...common, ...o.min !== void 0 ? { minval: o.min } : {}, ...o.max !== void 0 ? { maxval: o.max } : {}, ...o.step !== void 0 ? { step: o.step } : {}, ...o.options ? { options: o.options } : {} };
|
|
208
|
+
switch (type) {
|
|
209
|
+
case "int":
|
|
210
|
+
return import_index.input.int(d, title, numeric);
|
|
211
|
+
case "float":
|
|
212
|
+
return import_index.input.float(d, title, numeric);
|
|
213
|
+
case "bool":
|
|
214
|
+
return import_index.input.bool(d, title, common);
|
|
215
|
+
case "source":
|
|
216
|
+
return import_index.input.source(d, title, common);
|
|
217
|
+
case "color":
|
|
218
|
+
return import_index.input.color(colorOf(d), title, common);
|
|
219
|
+
default:
|
|
220
|
+
return import_index.input.string(String(d), title, { ...common, ...o.options ? { options: o.options.map(String) } : {} });
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
function indicatorBodyFromJson(spec) {
|
|
224
|
+
const parsed = parseSpec(spec);
|
|
225
|
+
const errors = checkIndicatorJson(parsed);
|
|
226
|
+
if (errors.length) throw new import_index.ScriptError(`The indicator "${parsed.title ?? "?"}" has ${errors.length === 1 ? "a mistake" : `${errors.length} mistakes`}:
|
|
227
|
+
- ${errors.join("\n- ")}`);
|
|
228
|
+
const s = parsed;
|
|
229
|
+
return () => {
|
|
230
|
+
(0, import_index.indicator)(s.title, { ...s.shortTitle ? { shorttitle: s.shortTitle } : {}, pane: s.pane ?? "auto" });
|
|
231
|
+
const vars = {};
|
|
232
|
+
const asVar = (v) => typeof v === "string" ? void 0 : v;
|
|
233
|
+
const texts = {};
|
|
234
|
+
for (const [id, v] of Object.entries(s.inputs ?? {})) {
|
|
235
|
+
const value = declareInput(id, v);
|
|
236
|
+
const x = asVar(value);
|
|
237
|
+
if (x !== void 0) vars[id] = x;
|
|
238
|
+
else texts[id] = value;
|
|
239
|
+
}
|
|
240
|
+
const calc = (text, where) => {
|
|
241
|
+
try {
|
|
242
|
+
return (0, import_formula.evaluateFormula)(withTexts(text, texts), vars);
|
|
243
|
+
} catch (err) {
|
|
244
|
+
if (err instanceof import_index.ScriptError) throw new import_index.ScriptError(`${where}: ${err.message}`);
|
|
245
|
+
throw err;
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
for (const [id, f] of Object.entries(s.values ?? {})) vars[id] = calc(f, `values.${id}`);
|
|
249
|
+
const handles = /* @__PURE__ */ new Map();
|
|
250
|
+
(s.plots ?? []).forEach((p, k) => {
|
|
251
|
+
const value = calc(p.value, `plots[${k}]`);
|
|
252
|
+
const fixed = p.color !== void 0 ? colorOf(p.color) : void 0;
|
|
253
|
+
const perBar = p.colorWhen ? import_index.color.when(asSeriesOf(calc(p.colorWhen.when, `plots[${k}].colorWhen`)), colorOf(p.colorWhen.color), p.colorWhen.else !== void 0 ? colorOf(p.colorWhen.else) : void 0) : void 0;
|
|
254
|
+
const style = p.style === "stepline" ? "stepline" : p.style;
|
|
255
|
+
handles.set(p.title, (0, import_index.plot)(value, p.title, { ...perBar ? { color: perBar } : fixed ? { color: fixed } : {}, ...p.width ? { linewidth: p.width } : {}, ...style ? { style } : {} }));
|
|
256
|
+
vars[slugName(p.title)] ??= value;
|
|
257
|
+
});
|
|
258
|
+
(s.levels ?? []).forEach((l) => {
|
|
259
|
+
const title = l.title ?? String(l.value);
|
|
260
|
+
handles.set(title, (0, import_index.hline)(l.value, title, { ...l.color ? { color: colorOf(l.color) } : {}, ...l.style ? { linestyle: l.style } : {} }));
|
|
261
|
+
});
|
|
262
|
+
(s.fills ?? []).forEach((f, k) => {
|
|
263
|
+
const [a, b] = f.between.map((t) => {
|
|
264
|
+
const h = handles.get(t);
|
|
265
|
+
if (!h) throw new import_index.ScriptError(`fills[${k}]: there is no plot or level titled "${t}". The titles are: ${[...handles.keys()].join(", ")}.`);
|
|
266
|
+
return h;
|
|
267
|
+
});
|
|
268
|
+
if (a.kind !== b.kind) throw new import_index.ScriptError(`fills[${k}]: a fill is between two plots or between two levels, not a plot and a level.`);
|
|
269
|
+
(0, import_index.fill)(a, b, { color: faded(colorOf(f.color), f.opacity ?? 0.15) });
|
|
270
|
+
});
|
|
271
|
+
(s.signals ?? []).forEach((g, k) => {
|
|
272
|
+
const when = asSeriesOf(calc(g.when, `signals[${k}]`));
|
|
273
|
+
const position = POSITIONS[g.position ?? "below"];
|
|
274
|
+
const shape = g.shape ?? (position === "abovebar" || position === "top" ? "triangledown" : "triangleup");
|
|
275
|
+
(0, import_index.plotshape)(when, g.title, {
|
|
276
|
+
style: shape,
|
|
277
|
+
location: position,
|
|
278
|
+
...g.color ? { color: colorOf(g.color) } : {},
|
|
279
|
+
...g.text ? { text: g.text } : {},
|
|
280
|
+
...g.size ? { size: g.size } : {}
|
|
281
|
+
});
|
|
282
|
+
if (g.alert) (0, import_index.alertcondition)(when, g.title, typeof g.alert === "string" ? g.alert : g.title);
|
|
283
|
+
});
|
|
284
|
+
(s.background ?? []).forEach((r, k) => {
|
|
285
|
+
(0, import_index.bgcolor)(import_index.color.when(asSeriesOf(calc(r.when, `background[${k}]`)), faded(colorOf(r.color), r.opacity ?? 0.15)), { ...r.title ? { title: r.title } : {} });
|
|
286
|
+
});
|
|
287
|
+
(s.barColors ?? []).forEach((r, k) => {
|
|
288
|
+
(0, import_index.barcolor)(import_index.color.when(asSeriesOf(calc(r.when, `barColors[${k}]`)), faded(colorOf(r.color), r.opacity ?? 1)), { ...r.title ? { title: r.title } : {} });
|
|
289
|
+
});
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
const slugName = (title) => title.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").replace(/^(\d)/, "_$1") || "plot";
|
|
293
|
+
function asSeriesOf(v) {
|
|
294
|
+
return typeof v === "number" ? import_series.Series.constant(import_index.close.barData, v) : v;
|
|
295
|
+
}
|
|
296
|
+
function withTexts(text, texts) {
|
|
297
|
+
return text.replace(/\b([A-Za-z_]\w*)\s*(==|!=|=)\s*"([^"]*)"/g, (all, id, op, value) => {
|
|
298
|
+
if (!(id in texts)) return all;
|
|
299
|
+
const same = texts[id] === value;
|
|
300
|
+
return op === "!=" ? same ? "0" : "1" : same ? "1" : "0";
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
function parseSpec(spec) {
|
|
304
|
+
if (typeof spec !== "string") return spec;
|
|
305
|
+
try {
|
|
306
|
+
return JSON.parse(spec);
|
|
307
|
+
} catch (err) {
|
|
308
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
309
|
+
const pos = /position (\d+)/.exec(msg);
|
|
310
|
+
let where = "";
|
|
311
|
+
if (pos) {
|
|
312
|
+
const before = spec.slice(0, Number(pos[1]));
|
|
313
|
+
where = ` (line ${before.split("\n").length}, column ${before.length - before.lastIndexOf("\n")})`;
|
|
314
|
+
}
|
|
315
|
+
throw new import_index.ScriptError(`The indicator is not valid JSON${where}: ${msg}. Check the commas between fields and the double quotes around names and texts.`);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
function defineIndicatorFromJson(spec, options = {}) {
|
|
319
|
+
return (0, import_define.defineIndicator)(indicatorBodyFromJson(spec), options);
|
|
320
|
+
}
|
|
321
|
+
//# sourceMappingURL=json.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/script/json.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Indicators described in JSON, without code: the settings, the calculations as formulas (see `formula()`), what to\n * draw and when to signal. `defineIndicatorFromJson(spec)` makes a ready-to-use indicator of it (`defineIndicator`).\n * Not a PineScript feature.\n */\nimport { Series } from '../runtime/series.js';\nimport { isColorText } from '../color/parse.js';\nimport {\n ScriptError,\n indicator,\n input,\n plot,\n hline,\n fill,\n plotshape,\n bgcolor,\n barcolor,\n alertcondition,\n color,\n close,\n type PlotHandle,\n} from './index.js';\nimport { evaluateFormula, type FormulaVariables } from './formula.js';\nimport { defineIndicator, type DefineIndicatorOptions, type IndicatorDefinition } from './define.js';\n\n/** A setting: its default value alone (`14`, `true`, `\"EMA\"`), or the default with its details. */\nexport type JsonInput =\n | number\n | boolean\n | string\n | {\n default: number | boolean | string;\n title?: string;\n /** 'int', 'float', 'bool', 'text', 'source' (a price: \"close\", \"hl2\"...) or 'color'; default: from the default value. */\n type?: 'int' | 'float' | 'bool' | 'text' | 'source' | 'color';\n min?: number;\n max?: number;\n step?: number;\n /** The values to choose from. */\n options?: Array<string | number>;\n tooltip?: string;\n group?: string;\n };\n\n/** A colour: a name (\"red\", \"teal\"...), \"#ff0000\" or \"rgba(255, 0, 0, 0.5)\". */\nexport type JsonColor = string;\n\nexport interface JsonPlot {\n title: string;\n /** The formula of the line. */\n value: string;\n color?: JsonColor;\n /** A colour where a formula is true, e.g. { \"when\": \"value > value[1]\", \"color\": \"green\", \"else\": \"red\" }. */\n colorWhen?: { when: string; color: JsonColor; else?: JsonColor };\n width?: number;\n style?: 'line' | 'histogram' | 'columns' | 'area' | 'circles' | 'stepline' | 'cross';\n}\n\nexport interface JsonLevel {\n title?: string;\n value: number;\n color?: JsonColor;\n style?: 'solid' | 'dashed' | 'dotted';\n}\n\nexport interface JsonFill {\n /** The titles of two plots, or of two levels. */\n between: [string, string];\n color: JsonColor;\n /** 0 (invisible) to 1 (solid); default 0.15. */\n opacity?: number;\n}\n\nexport interface JsonSignal {\n title: string;\n /** The formula of the condition. */\n when: string;\n shape?: 'triangleup' | 'triangledown' | 'arrowup' | 'arrowdown' | 'circle' | 'square' | 'diamond' | 'cross' | 'xcross' | 'flag' | 'labelup' | 'labeldown';\n /** Where it is drawn: 'above' or 'below' the bar, at the 'top' or 'bottom' of the pane. */\n position?: 'above' | 'below' | 'top' | 'bottom';\n color?: JsonColor;\n text?: string;\n size?: 'tiny' | 'small' | 'normal' | 'large' | 'huge';\n /** An alert an app can offer: true (the title as message) or the message. */\n alert?: boolean | string;\n}\n\nexport interface JsonColorRule {\n title?: string;\n when: string;\n color: JsonColor;\n /** 0 (invisible) to 1 (solid); default 1 for bar colours, 0.15 for backgrounds. */\n opacity?: number;\n}\n\n/** An indicator in JSON. */\nexport interface IndicatorJson {\n /** Optional, for editors: the JSON schema. */\n $schema?: string;\n title: string;\n shortTitle?: string;\n /** 'price' (on the price chart), 'separate' (its own pane) or 'auto' (default: chosen from the values). */\n pane?: 'price' | 'separate' | 'auto';\n /** The settings, by id: the names the formulas use and the names of the values given to `calculate`. */\n inputs?: Record<string, JsonInput>;\n /** Named calculations, in order: each formula can use the settings and the values before it. */\n values?: Record<string, string>;\n plots?: JsonPlot[];\n levels?: JsonLevel[];\n fills?: JsonFill[];\n signals?: JsonSignal[];\n background?: JsonColorRule[];\n barColors?: JsonColorRule[];\n}\n\n// \u2500\u2500 Checks \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst KEYS: Record<string, readonly string[]> = {\n indicator: ['$schema', 'title', 'shortTitle', 'pane', 'inputs', 'values', 'plots', 'levels', 'fills', 'signals', 'background', 'barColors'],\n input: ['default', 'title', 'type', 'min', 'max', 'step', 'options', 'tooltip', 'group'],\n plot: ['title', 'value', 'color', 'colorWhen', 'width', 'style'],\n colorWhen: ['when', 'color', 'else'],\n level: ['title', 'value', 'color', 'style'],\n fill: ['between', 'color', 'opacity'],\n signal: ['title', 'when', 'shape', 'position', 'color', 'text', 'size', 'alert'],\n rule: ['title', 'when', 'color', 'opacity'],\n};\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\n\nfunction closest(name: string, names: readonly string[]): string | undefined {\n const n = name.toLowerCase();\n let best: string | undefined;\n let bestD = Infinity;\n for (const k of names) {\n const a = n;\n const b = k.toLowerCase();\n const row = Array.from({ length: b.length + 1 }, (_, j) => j);\n for (let i = 1; i <= a.length; i++) {\n let diag = row[0]!;\n row[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const up = row[j]!;\n row[j] = Math.min(up + 1, row[j - 1]! + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));\n diag = up;\n }\n }\n if (row[b.length]! < bestD) {\n bestD = row[b.length]!;\n best = k;\n }\n }\n if (bestD <= Math.max(2, Math.floor(name.length / 3))) return best;\n // a longer or shorter form of a field: \"minimum\" for \"min\"\n return names.find((k) => k.length >= 3 && (n.startsWith(k.toLowerCase()) || k.toLowerCase().startsWith(n)));\n}\n\nclass Checker {\n readonly errors: string[] = [];\n error(where: string, msg: string): void {\n this.errors.push(`${where}: ${msg}`);\n }\n keys(where: string, o: Record<string, unknown>, kind: string, required: string[] = []): void {\n for (const k of Object.keys(o)) {\n if (KEYS[kind]!.includes(k)) continue;\n const near = closest(k, KEYS[kind]!);\n this.error(where, `there is no field \"${k}\".` + (near ? ` Did you mean \"${near}\"?` : '') + ` The fields are: ${KEYS[kind]!.join(', ')}.`);\n }\n for (const k of required) if (o[k] === undefined) this.error(where, `\"${k}\" is missing.`);\n }\n text(where: string, v: unknown, name: string): void {\n if (v !== undefined && (typeof v !== 'string' || !v.trim())) this.error(where, `\"${name}\" is a text.`);\n }\n oneOf(where: string, v: unknown, name: string, list: readonly string[]): void {\n if (v !== undefined && !list.includes(v as string)) this.error(where, `\"${name}\" is one of ${list.map((x) => `\"${x}\"`).join(', ')}, got ${JSON.stringify(v)}.`);\n }\n color(where: string, v: unknown, name: string): void {\n if (v !== undefined && colorOf(v) === undefined) {\n this.error(where, `\"${name}\" ${JSON.stringify(v)} is not a colour: write a name (${COLOR_NAMES.join(', ')}), \"#ff0000\" or \"rgba(255, 0, 0, 0.5)\".`);\n }\n }\n opacity(where: string, v: unknown): void {\n if (v !== undefined && !(typeof v === 'number' && v >= 0 && v <= 1)) this.error(where, `\"opacity\" is from 0 (invisible) to 1 (solid), got ${JSON.stringify(v)}.`);\n }\n}\n\nconst COLOR_NAMES = ['aqua', 'black', 'blue', 'fuchsia', 'gray', 'green', 'lime', 'maroon', 'navy', 'olive', 'orange', 'purple', 'red', 'silver', 'teal', 'white', 'yellow'];\nconst SHAPES = ['triangleup', 'triangledown', 'arrowup', 'arrowdown', 'circle', 'square', 'diamond', 'cross', 'xcross', 'flag', 'labelup', 'labeldown'];\nconst POSITIONS: Record<string, string> = { above: 'abovebar', below: 'belowbar', top: 'top', bottom: 'bottom' };\nconst STYLES = ['line', 'histogram', 'columns', 'area', 'circles', 'stepline', 'cross'];\nconst SOURCES = ['open', 'high', 'low', 'close', 'volume', 'hl2', 'hlc3', 'ohlc4', 'hlcc4'];\n\nfunction colorOf(v: unknown): string | undefined {\n if (typeof v !== 'string') return undefined;\n const name = v.trim().toLowerCase();\n if (COLOR_NAMES.includes(name)) return (color as unknown as Record<string, string>)[name];\n return isColorText(v) ? v.trim() : undefined;\n}\n\n/**\n * Host-side: the mistakes of an indicator in JSON, one message each (\"plots[1]: \"value\" is missing.\"); empty when\n * there are none. The formulas are checked when the indicator runs. A script does not call it.\n * @param spec - The indicator in JSON, as parsed (an object).\n * @returns One message per mistake.\n */\nexport function checkIndicatorJson(spec: unknown): string[] {\n const c = new Checker();\n if (!isObject(spec)) return ['the indicator is a JSON object: { \"title\": \"...\", \"plots\": [...] }.'];\n c.keys('indicator', spec, 'indicator', ['title']);\n c.text('indicator', spec.title, 'title');\n c.text('indicator', spec.shortTitle, 'shortTitle');\n c.oneOf('indicator', spec.pane, 'pane', ['price', 'separate', 'auto']);\n const names = new Set<string>();\n const name = (where: string, id: string): void => {\n if (!/^[A-Za-z_]\\w*$/.test(id)) c.error(where, `the name \"${id}\" has letters, digits and _ only, and does not start with a digit.`);\n if (names.has(id)) c.error(where, `the name \"${id}\" is used twice.`);\n names.add(id);\n };\n if (spec.inputs !== undefined) {\n if (!isObject(spec.inputs)) c.error('inputs', 'the settings are an object: { \"length\": 14 }.');\n else\n for (const [id, v] of Object.entries(spec.inputs)) {\n const where = `inputs.${id}`;\n name(where, id);\n if (isObject(v)) {\n c.keys(where, v, 'input', ['default']);\n c.oneOf(where, v.type, 'type', ['int', 'float', 'bool', 'text', 'source', 'color']);\n if (v.type === 'source' && !SOURCES.includes(v.default as string)) c.error(where, `a source is one of ${SOURCES.join(', ')}.`);\n if (v.type === 'color') c.color(where, v.default, 'default');\n if (v.options !== undefined && (!Array.isArray(v.options) || !v.options.includes(v.default as string))) c.error(where, '\"options\" is a list that holds the default.');\n for (const k of ['min', 'max', 'step'] as const) if (v[k] !== undefined && typeof v[k] !== 'number') c.error(where, `\"${k}\" is a number.`);\n } else if (!['number', 'boolean', 'string'].includes(typeof v)) {\n c.error(where, 'a setting is a number, true / false, a text, or { \"default\": ..., \"title\": ... }.');\n }\n }\n }\n if (spec.values !== undefined) {\n if (!isObject(spec.values)) c.error('values', 'the values are an object of formulas: { \"fast\": \"ema(close, 9)\" }.');\n else\n for (const [id, f] of Object.entries(spec.values)) {\n name(`values.${id}`, id);\n c.text(`values.${id}`, f, 'formula');\n }\n }\n const list = (key: string, check: (where: string, o: Record<string, unknown>) => void): void => {\n const v = spec[key];\n if (v === undefined) return;\n if (!Array.isArray(v)) return c.error(key, 'is a list: [ { ... }, { ... } ].');\n v.forEach((o, k) => (isObject(o) ? check(`${key}[${k}]`, o) : c.error(`${key}[${k}]`, 'is an object { ... }.')));\n };\n list('plots', (w, o) => {\n c.keys(w, o, 'plot', ['title', 'value']);\n c.text(w, o.title, 'title');\n c.text(w, o.value, 'value');\n c.color(w, o.color, 'color');\n c.oneOf(w, o.style, 'style', STYLES);\n if (o.width !== undefined && !(typeof o.width === 'number' && o.width >= 1 && o.width <= 4)) c.error(w, '\"width\" is 1 to 4.');\n if (o.colorWhen !== undefined) {\n if (!isObject(o.colorWhen)) c.error(w, '\"colorWhen\" is { \"when\": \"...\", \"color\": \"...\", \"else\": \"...\" }.');\n else {\n c.keys(`${w}.colorWhen`, o.colorWhen, 'colorWhen', ['when', 'color']);\n c.color(`${w}.colorWhen`, o.colorWhen.color, 'color');\n c.color(`${w}.colorWhen`, o.colorWhen.else, 'else');\n }\n }\n });\n list('levels', (w, o) => {\n c.keys(w, o, 'level', ['value']);\n if (o.value !== undefined && typeof o.value !== 'number') c.error(w, '\"value\" is a number.');\n c.color(w, o.color, 'color');\n c.oneOf(w, o.style, 'style', ['solid', 'dashed', 'dotted']);\n });\n list('fills', (w, o) => {\n c.keys(w, o, 'fill', ['between', 'color']);\n if (o.between !== undefined && !(Array.isArray(o.between) && o.between.length === 2 && o.between.every((x) => typeof x === 'string'))) {\n c.error(w, '\"between\" is the titles of two plots or two levels: [\"Upper\", \"Lower\"].');\n }\n c.color(w, o.color, 'color');\n c.opacity(w, o.opacity);\n });\n list('signals', (w, o) => {\n c.keys(w, o, 'signal', ['title', 'when']);\n c.text(w, o.when, 'when');\n c.oneOf(w, o.shape, 'shape', SHAPES);\n c.oneOf(w, o.position, 'position', Object.keys(POSITIONS));\n c.oneOf(w, o.size, 'size', ['tiny', 'small', 'normal', 'large', 'huge']);\n c.color(w, o.color, 'color');\n if (o.alert !== undefined && typeof o.alert !== 'boolean' && typeof o.alert !== 'string') c.error(w, '\"alert\" is true or the alert message.');\n });\n for (const key of ['background', 'barColors']) {\n list(key, (w, o) => {\n c.keys(w, o, 'rule', ['when', 'color']);\n c.text(w, o.when, 'when');\n c.color(w, o.color, 'color');\n c.opacity(w, o.opacity);\n });\n }\n return c.errors;\n}\n\n// \u2500\u2500 The script \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst faded = (c: string, opacity: number): string => (opacity >= 1 ? c : color.fade(c, 1 - opacity));\n\nfunction declareInput(id: string, v: JsonInput): number | boolean | string | Series {\n const o = isObject(v) ? (v as Exclude<JsonInput, number | boolean | string>) : { default: v };\n const title = o.title ?? id;\n const common = { id, ...(o.tooltip ? { tooltip: o.tooltip } : {}), ...(o.group ? { group: o.group } : {}) };\n const d = o.default;\n const type = o.type ?? (typeof d === 'boolean' ? 'bool' : typeof d === 'number' ? (Number.isInteger(d) && !(o.step && !Number.isInteger(o.step)) ? 'int' : 'float') : 'text');\n const numeric = { ...common, ...(o.min !== undefined ? { minval: o.min } : {}), ...(o.max !== undefined ? { maxval: o.max } : {}), ...(o.step !== undefined ? { step: o.step } : {}), ...(o.options ? { options: o.options as number[] } : {}) };\n switch (type) {\n case 'int':\n return input.int(d as number, title, numeric);\n case 'float':\n return input.float(d as number, title, numeric);\n case 'bool':\n return input.bool(d as boolean, title, common);\n case 'source':\n return input.source(d as string, title, common);\n case 'color':\n return input.color(colorOf(d)!, title, common);\n default:\n return input.string(String(d), title, { ...common, ...(o.options ? { options: o.options.map(String) } : {}) });\n }\n}\n\n/**\n * Host-side: the script body of an indicator in JSON (for `executeScript`, or a host's own runner). A script does not\n * call it.\n * @param spec - The indicator in JSON: an object, or its text.\n * @returns The script body. Throws on a mistake in the JSON.\n */\nexport function indicatorBodyFromJson(spec: IndicatorJson | string): () => void {\n const parsed = parseSpec(spec);\n const errors = checkIndicatorJson(parsed);\n if (errors.length) throw new ScriptError(`The indicator \"${(parsed as { title?: string }).title ?? '?'}\" has ${errors.length === 1 ? 'a mistake' : `${errors.length} mistakes`}:\\n- ${errors.join('\\n- ')}`);\n const s = parsed as IndicatorJson;\n return () => {\n indicator(s.title, { ...(s.shortTitle ? { shorttitle: s.shortTitle } : {}), pane: s.pane ?? 'auto' });\n const vars: FormulaVariables = {};\n const asVar = (v: number | boolean | string | Series): number | boolean | Series | undefined => (typeof v === 'string' ? undefined : v);\n const texts: Record<string, string> = {};\n for (const [id, v] of Object.entries(s.inputs ?? {})) {\n const value = declareInput(id, v);\n const x = asVar(value);\n if (x !== undefined) vars[id] = x;\n else texts[id] = value as string;\n }\n // a text setting is only compared in a formula (mode == \"EMA\"): the comparison is replaced by 1 or 0\n const calc = (text: string, where: string): Series | number => {\n try {\n return evaluateFormula(withTexts(text, texts), vars);\n } catch (err) {\n if (err instanceof ScriptError) throw new ScriptError(`${where}: ${err.message}`);\n throw err;\n }\n };\n for (const [id, f] of Object.entries(s.values ?? {})) vars[id] = calc(f, `values.${id}`);\n const handles = new Map<string, PlotHandle>();\n (s.plots ?? []).forEach((p, k) => {\n const value = calc(p.value, `plots[${k}]`);\n const fixed = p.color !== undefined ? colorOf(p.color) : undefined;\n const perBar = p.colorWhen ? color.when(asSeriesOf(calc(p.colorWhen.when, `plots[${k}].colorWhen`)), colorOf(p.colorWhen.color)!, p.colorWhen.else !== undefined ? colorOf(p.colorWhen.else) : undefined) : undefined;\n const style = p.style === 'stepline' ? 'stepline' : p.style;\n handles.set(p.title, plot(value, p.title, { ...(perBar ? { color: perBar as string[] } : fixed ? { color: fixed } : {}), ...(p.width ? { linewidth: p.width } : {}), ...(style ? { style } : {}) }));\n vars[slugName(p.title)] ??= value as Series;\n });\n (s.levels ?? []).forEach((l) => {\n const title = l.title ?? String(l.value);\n handles.set(title, hline(l.value, title, { ...(l.color ? { color: colorOf(l.color) } : {}), ...(l.style ? { linestyle: l.style } : {}) }));\n });\n (s.fills ?? []).forEach((f, k) => {\n const [a, b] = f.between.map((t) => {\n const h = handles.get(t);\n if (!h) throw new ScriptError(`fills[${k}]: there is no plot or level titled \"${t}\". The titles are: ${[...handles.keys()].join(', ')}.`);\n return h;\n });\n if (a!.kind !== b!.kind) throw new ScriptError(`fills[${k}]: a fill is between two plots or between two levels, not a plot and a level.`);\n fill(a!, b!, { color: faded(colorOf(f.color)!, f.opacity ?? 0.15) });\n });\n (s.signals ?? []).forEach((g, k) => {\n const when = asSeriesOf(calc(g.when, `signals[${k}]`));\n const position = POSITIONS[g.position ?? 'below']!;\n const shape = g.shape ?? (position === 'abovebar' || position === 'top' ? 'triangledown' : 'triangleup');\n plotshape(when, g.title, {\n style: shape as never,\n location: position as never,\n ...(g.color ? { color: colorOf(g.color) } : {}),\n ...(g.text ? { text: g.text } : {}),\n ...(g.size ? { size: g.size as never } : {}),\n });\n if (g.alert) alertcondition(when, g.title, typeof g.alert === 'string' ? g.alert : g.title);\n });\n (s.background ?? []).forEach((r, k) => {\n bgcolor(color.when(asSeriesOf(calc(r.when, `background[${k}]`)), faded(colorOf(r.color)!, r.opacity ?? 0.15)), { ...(r.title ? { title: r.title } : {}) });\n });\n (s.barColors ?? []).forEach((r, k) => {\n barcolor(color.when(asSeriesOf(calc(r.when, `barColors[${k}]`)), faded(colorOf(r.color)!, r.opacity ?? 1)), { ...(r.title ? { title: r.title } : {}) });\n });\n };\n}\n\n/** A plot title as a formula name: \"Fast MA\" gives fast_ma. */\nconst slugName = (title: string): string => title.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').replace(/^(\\d)/, '_$1') || 'plot';\n\n/** A condition that gives a number (no Series used) as a Series. */\nfunction asSeriesOf(v: Series | number): Series {\n return typeof v === 'number' ? Series.constant(close.barData, v) : v;\n}\n\n/** A text setting compared in a formula (`mode == \"EMA\"`): the comparison becomes 1 or 0. */\nfunction withTexts(text: string, texts: Record<string, string>): string {\n return text.replace(/\\b([A-Za-z_]\\w*)\\s*(==|!=|=)\\s*\"([^\"]*)\"/g, (all, id: string, op: string, value: string) => {\n if (!(id in texts)) return all;\n const same = texts[id] === value;\n return op === '!=' ? (same ? '0' : '1') : same ? '1' : '0';\n });\n}\n\nfunction parseSpec(spec: IndicatorJson | string): unknown {\n if (typeof spec !== 'string') return spec;\n try {\n return JSON.parse(spec);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const pos = /position (\\d+)/.exec(msg);\n let where = '';\n if (pos) {\n const before = spec.slice(0, Number(pos[1]));\n where = ` (line ${before.split('\\n').length}, column ${before.length - before.lastIndexOf('\\n')})`;\n }\n throw new ScriptError(`The indicator is not valid JSON${where}: ${msg}. Check the commas between fields and the double quotes around names and texts.`);\n }\n}\n\n/**\n * Host-side: an indicator described in JSON (an object or its text), ready to use: the same as `defineIndicator` of\n * its script. A script does not call it.\n *\n * ```js\n * const cross = defineIndicatorFromJson({\n * title: 'Average cross',\n * inputs: { fast: 9, slow: 21 },\n * values: { fastLine: 'ema(close, fast)', slowLine: 'ema(close, slow)' },\n * plots: [{ title: 'Fast', value: 'fastLine', color: 'teal' }, { title: 'Slow', value: 'slowLine', color: 'orange' }],\n * signals: [{ title: 'Buy', when: 'crossover(fastLine, slowLine)', position: 'below', color: 'green', alert: true }],\n * });\n * cross.calculate(bars, { fast: 5 });\n * ```\n * @param spec - The indicator in JSON: an object, or its text.\n * @param options - Strict mode and the other run options. Default: `{}`.\n * @returns The indicator, as `defineIndicator` gives it. Throws on a mistake in the JSON.\n */\nexport function defineIndicatorFromJson(spec: IndicatorJson | string, options: DefineIndicatorOptions = {}): IndicatorDefinition {\n return defineIndicator(indicatorBodyFromJson(spec), options);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAK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bar of a higher timeframe), with lookahead off as well; a lower timeframe keeps the rules
|
|
22
22
|
* above (the last lower bar so far with lookahead off, the first one of the chart bar with lookahead on)
|
|
23
23
|
*
|
|
24
|
+
* Tick timeframes ("1T", "10T"…, #214): a tick bar has no duration, so it is placed by its open time. A chart bar
|
|
25
|
+
* holds the tick bars that open at or after its open and before its close; lookahead off shows the last tick bar
|
|
26
|
+
* that opened before the close of the chart bar, lookahead on the last one that opened at or before its open. On a
|
|
27
|
+
* chart of ticks, a bar closes when the next one opens (the last one is still open): it shows the bars that closed
|
|
28
|
+
* before then.
|
|
29
|
+
*
|
|
24
30
|
* Close times, trading days and time zones come from the exchange calendars of the chart and of the other symbol
|
|
25
31
|
* (time zone and session, read by the session functions). Without them:
|
|
26
32
|
* - a symbol that trades every day (bars on Saturdays or Sundays; W bars at Monday 00:00 UTC; M bars on the first day
|
|
@@ -62,8 +68,7 @@ export interface OtherSymbolChart extends SymbolCalendar {
|
|
|
62
68
|
* for na (#179). `otherBars` are the bars of the other symbol on `tf` ("" for the chart timeframe, or a higher
|
|
63
69
|
* or a lower one), with times in the unit of the chart bars. Rules in the module notes; the same rules hold for a
|
|
64
70
|
* lower timeframe (#181): lookahead off shows the last lower bar that closes by the close of the chart bar, lookahead
|
|
65
|
-
* on the last one that opened by its open. It also serves the chart symbol on a lower timeframe.
|
|
66
|
-
* @throws RangeError for a tick timeframe
|
|
71
|
+
* on the last one that opened by its open. It also serves the chart symbol on a lower timeframe, and ticks (#214).
|
|
67
72
|
*/
|
|
68
73
|
export declare function securityOther(chartBars: ReadonlyArray<{
|
|
69
74
|
time: number;
|
|
@@ -74,7 +79,7 @@ export declare function securityOther(chartBars: ReadonlyArray<{
|
|
|
74
79
|
* PineScript `request.security_lower_tf` (#181): for each chart bar, the range `[from, to)` of the bars of
|
|
75
80
|
* `otherBars` (a lower timeframe, the chart symbol or another one) that it contains: the bars whose close time is
|
|
76
81
|
* after the open of the chart bar and at or before its close (a 13:00 hourly bar of a 24x7 symbol is in a 13:30 stock
|
|
77
|
-
* day, which closes at 20:00). An empty range for a chart bar without such bars.
|
|
82
|
+
* day, which closes at 20:00); tick bars by their open time (#214). An empty range for a chart bar without such bars.
|
|
78
83
|
*
|
|
79
84
|
* As PineScript, at most the last {@link MAX_INTRABARS} (100,000) lower-timeframe bars are given out
|
|
80
85
|
* (`options.maxIntrabars` changes it): the older chart bars get an empty range (#192).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"other.d.ts","sourceRoot":"","sources":["../../../src/security/other.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"other.d.ts","sourceRoot":"","sources":["../../../src/security/other.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAIH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAI1D,2FAA2F;AAC3F,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,WAAW,GAAG,MAAM,CAAC;CAChC;AAED,wCAAwC;AACxC,MAAM,WAAW,kBAAkB;IACjC,wDAAwD;IACxD,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,mDAAmD;IACnD,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,0EAA0E;IAC1E,KAAK,CAAC,EAAE,cAAc,CAAC;CACxB;AAED,wFAAwF;AACxF,MAAM,WAAW,gBAAiB,SAAQ,cAAc;IACtD,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,mDAAmD;IACnD,QAAQ,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC;IACtB,8DAA8D;IAC9D,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B;AAsID;;;;;;GAMG;AACH,wBAAgB,aAAa,CAC3B,SAAS,EAAE,aAAa,CAAC;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,EAC1C,SAAS,EAAE,aAAa,CAAC;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,EAC1C,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,gBAAgB,EACvB,OAAO,GAAE,kBAAuB,GAC/B,MAAM,EAAE,CAuCV;AAED;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,SAAS,EAAE,aAAa,CAAC;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,EAC1C,SAAS,EAAE,aAAa,CAAC;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,EAC1C,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,gBAAgB,EACvB,OAAO,GAAE,IAAI,CAAC,kBAAkB,EAAE,OAAO,CAAC,GAAG;IAAE,YAAY,CAAC,EAAE,MAAM,CAAA;CAAO,GAC1E,KAAK,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAwBzB;AAED,yGAAyG;AACzG,eAAO,MAAM,aAAa,SAAU,CAAC;AAErC;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,aAAa,CAAC;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,EAC1C,SAAS,EAAE,aAAa,CAAC;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,EAC1C,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,EACzB,KAAK,EAAE,gBAAgB,EACvB,OAAO,GAAE,kBAAuB,GAC/B,MAAM,EAAE,CAEV"}
|
|
@@ -86,6 +86,7 @@ function closeTimes(times, tf, zone) {
|
|
|
86
86
|
const calendar = calendarOf(zone, tf);
|
|
87
87
|
const info = timeframe.info(tf);
|
|
88
88
|
const len = timeframe.in_seconds(tf) * 1e3;
|
|
89
|
+
if (info.isticks) return times.map((_, i) => i + 1 < times.length ? times[i + 1] : Infinity);
|
|
89
90
|
return times.map((t, i) => {
|
|
90
91
|
if (calendar) {
|
|
91
92
|
const c = (0, import_context.periodClose)(t, tf, calendar);
|
|
@@ -115,11 +116,17 @@ function latestAtOrBefore(keys, at) {
|
|
|
115
116
|
return j;
|
|
116
117
|
});
|
|
117
118
|
}
|
|
119
|
+
function firstAtOrAfter(keys, at) {
|
|
120
|
+
let j = 0;
|
|
121
|
+
return at.map((x) => {
|
|
122
|
+
while (j < keys.length && keys[j] < x) j++;
|
|
123
|
+
return j;
|
|
124
|
+
});
|
|
125
|
+
}
|
|
118
126
|
const zoneOf = (c) => c?.timezone && c.session ? { timezone: c.timezone, session: c.session } : null;
|
|
119
127
|
function setup(ct, ot, tf, chart, options) {
|
|
120
128
|
const chartTf = timeframe.info(chart.timeframe).period;
|
|
121
129
|
const otherTf = tf.trim() === "" ? chartTf : timeframe.info(tf).period;
|
|
122
|
-
if (timeframe.info(otherTf).isticks) throw new RangeError(`request.security: tick timeframe "${tf}" is not supported.`);
|
|
123
130
|
const chartZone = zoneOf(chart) ?? (tradesEveryDay(ct, chartTf) ? UTC_24X7 : null);
|
|
124
131
|
const otherZone = zoneOf(options.other) ?? (tradesEveryDay(ot, otherTf) ? UTC_24X7 : chartZone && onCalendar(ot, otherTf, chartZone) ? chartZone : null);
|
|
125
132
|
return { chartTf, otherTf, chartZone, otherZone };
|
|
@@ -144,7 +151,9 @@ function securityOther(chartBars, otherBars, tf, chart, options = {}) {
|
|
|
144
151
|
on = latestAtOrBefore(ot, ct);
|
|
145
152
|
}
|
|
146
153
|
}
|
|
147
|
-
const
|
|
154
|
+
const chartClose = closeTimes(ct, chartTf, chartZone);
|
|
155
|
+
const before = (keys) => firstAtOrAfter(keys, chartClose).map((j) => j - 1);
|
|
156
|
+
const index = options.lookahead ? on : timeframe.info(otherTf).isticks ? before(ot) : timeframe.info(chartTf).isticks ? before(closeTimes(ot, otherTf, otherZone)) : latestAtOrBefore(closeTimes(ot, otherTf, otherZone), chartClose);
|
|
148
157
|
if (realtime) index[n - 1] = on[n - 1];
|
|
149
158
|
if (!options.gaps) return index;
|
|
150
159
|
return index.map((j, i) => i === 0 || j !== index[i - 1] ? j : -1);
|
|
@@ -154,10 +163,18 @@ function securityLowerTf(chartBars, otherBars, tf, chart, options = {}) {
|
|
|
154
163
|
const ct = chartBars.map((b) => b.time * unit);
|
|
155
164
|
const ot = otherBars.map((b) => b.time * unit);
|
|
156
165
|
const { chartTf, otherTf, chartZone, otherZone } = setup(ct, ot, tf, chart, options);
|
|
157
|
-
const
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
166
|
+
const chartClose = closeTimes(ct, chartTf, chartZone);
|
|
167
|
+
let ranges;
|
|
168
|
+
if (timeframe.info(otherTf).isticks) {
|
|
169
|
+
const from = firstAtOrAfter(ot, ct);
|
|
170
|
+
const to = firstAtOrAfter(ot, chartClose);
|
|
171
|
+
ranges = ct.map((_, i) => [from[i], Math.max(from[i], to[i])]);
|
|
172
|
+
} else {
|
|
173
|
+
const oc = closeTimes(ot, otherTf, otherZone);
|
|
174
|
+
const from = latestAtOrBefore(oc, ct);
|
|
175
|
+
const to = latestAtOrBefore(oc, chartClose);
|
|
176
|
+
ranges = ct.map((_, i) => [from[i] + 1, Math.max(from[i] + 1, to[i] + 1)]);
|
|
177
|
+
}
|
|
161
178
|
const max = options.maxIntrabars ?? MAX_INTRABARS;
|
|
162
179
|
const end = ranges.reduce((m, [, t]) => Math.max(m, t), 0);
|
|
163
180
|
const first = end - max;
|