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,457 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Indicators described in JSON, without code: the settings, the calculations as formulas (see `formula()`), what to
|
|
3
|
+
* draw and when to signal. `defineIndicatorFromJson(spec)` makes a ready-to-use indicator of it (`defineIndicator`).
|
|
4
|
+
* Not a PineScript feature.
|
|
5
|
+
*/
|
|
6
|
+
import { Series } from '../runtime/series.js';
|
|
7
|
+
import { isColorText } from '../color/parse.js';
|
|
8
|
+
import {
|
|
9
|
+
ScriptError,
|
|
10
|
+
indicator,
|
|
11
|
+
input,
|
|
12
|
+
plot,
|
|
13
|
+
hline,
|
|
14
|
+
fill,
|
|
15
|
+
plotshape,
|
|
16
|
+
bgcolor,
|
|
17
|
+
barcolor,
|
|
18
|
+
alertcondition,
|
|
19
|
+
color,
|
|
20
|
+
close,
|
|
21
|
+
type PlotHandle,
|
|
22
|
+
} from './index.js';
|
|
23
|
+
import { evaluateFormula, type FormulaVariables } from './formula.js';
|
|
24
|
+
import { defineIndicator, type DefineIndicatorOptions, type IndicatorDefinition } from './define.js';
|
|
25
|
+
|
|
26
|
+
/** A setting: its default value alone (`14`, `true`, `"EMA"`), or the default with its details. */
|
|
27
|
+
export type JsonInput =
|
|
28
|
+
| number
|
|
29
|
+
| boolean
|
|
30
|
+
| string
|
|
31
|
+
| {
|
|
32
|
+
default: number | boolean | string;
|
|
33
|
+
title?: string;
|
|
34
|
+
/** 'int', 'float', 'bool', 'text', 'source' (a price: "close", "hl2"...) or 'color'; default: from the default value. */
|
|
35
|
+
type?: 'int' | 'float' | 'bool' | 'text' | 'source' | 'color';
|
|
36
|
+
min?: number;
|
|
37
|
+
max?: number;
|
|
38
|
+
step?: number;
|
|
39
|
+
/** The values to choose from. */
|
|
40
|
+
options?: Array<string | number>;
|
|
41
|
+
tooltip?: string;
|
|
42
|
+
group?: string;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** A colour: a name ("red", "teal"...), "#ff0000" or "rgba(255, 0, 0, 0.5)". */
|
|
46
|
+
export type JsonColor = string;
|
|
47
|
+
|
|
48
|
+
export interface JsonPlot {
|
|
49
|
+
title: string;
|
|
50
|
+
/** The formula of the line. */
|
|
51
|
+
value: string;
|
|
52
|
+
color?: JsonColor;
|
|
53
|
+
/** A colour where a formula is true, e.g. { "when": "value > value[1]", "color": "green", "else": "red" }. */
|
|
54
|
+
colorWhen?: { when: string; color: JsonColor; else?: JsonColor };
|
|
55
|
+
width?: number;
|
|
56
|
+
style?: 'line' | 'histogram' | 'columns' | 'area' | 'circles' | 'stepline' | 'cross';
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface JsonLevel {
|
|
60
|
+
title?: string;
|
|
61
|
+
value: number;
|
|
62
|
+
color?: JsonColor;
|
|
63
|
+
style?: 'solid' | 'dashed' | 'dotted';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface JsonFill {
|
|
67
|
+
/** The titles of two plots, or of two levels. */
|
|
68
|
+
between: [string, string];
|
|
69
|
+
color: JsonColor;
|
|
70
|
+
/** 0 (invisible) to 1 (solid); default 0.15. */
|
|
71
|
+
opacity?: number;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface JsonSignal {
|
|
75
|
+
title: string;
|
|
76
|
+
/** The formula of the condition. */
|
|
77
|
+
when: string;
|
|
78
|
+
shape?: 'triangleup' | 'triangledown' | 'arrowup' | 'arrowdown' | 'circle' | 'square' | 'diamond' | 'cross' | 'xcross' | 'flag' | 'labelup' | 'labeldown';
|
|
79
|
+
/** Where it is drawn: 'above' or 'below' the bar, at the 'top' or 'bottom' of the pane. */
|
|
80
|
+
position?: 'above' | 'below' | 'top' | 'bottom';
|
|
81
|
+
color?: JsonColor;
|
|
82
|
+
text?: string;
|
|
83
|
+
size?: 'tiny' | 'small' | 'normal' | 'large' | 'huge';
|
|
84
|
+
/** An alert an app can offer: true (the title as message) or the message. */
|
|
85
|
+
alert?: boolean | string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface JsonColorRule {
|
|
89
|
+
title?: string;
|
|
90
|
+
when: string;
|
|
91
|
+
color: JsonColor;
|
|
92
|
+
/** 0 (invisible) to 1 (solid); default 1 for bar colours, 0.15 for backgrounds. */
|
|
93
|
+
opacity?: number;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** An indicator in JSON. */
|
|
97
|
+
export interface IndicatorJson {
|
|
98
|
+
/** Optional, for editors: the JSON schema. */
|
|
99
|
+
$schema?: string;
|
|
100
|
+
title: string;
|
|
101
|
+
shortTitle?: string;
|
|
102
|
+
/** 'price' (on the price chart), 'separate' (its own pane) or 'auto' (default: chosen from the values). */
|
|
103
|
+
pane?: 'price' | 'separate' | 'auto';
|
|
104
|
+
/** The settings, by id: the names the formulas use and the names of the values given to `calculate`. */
|
|
105
|
+
inputs?: Record<string, JsonInput>;
|
|
106
|
+
/** Named calculations, in order: each formula can use the settings and the values before it. */
|
|
107
|
+
values?: Record<string, string>;
|
|
108
|
+
plots?: JsonPlot[];
|
|
109
|
+
levels?: JsonLevel[];
|
|
110
|
+
fills?: JsonFill[];
|
|
111
|
+
signals?: JsonSignal[];
|
|
112
|
+
background?: JsonColorRule[];
|
|
113
|
+
barColors?: JsonColorRule[];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ── Checks ───────────────────────────────────────────────────────────────────
|
|
117
|
+
|
|
118
|
+
const KEYS: Record<string, readonly string[]> = {
|
|
119
|
+
indicator: ['$schema', 'title', 'shortTitle', 'pane', 'inputs', 'values', 'plots', 'levels', 'fills', 'signals', 'background', 'barColors'],
|
|
120
|
+
input: ['default', 'title', 'type', 'min', 'max', 'step', 'options', 'tooltip', 'group'],
|
|
121
|
+
plot: ['title', 'value', 'color', 'colorWhen', 'width', 'style'],
|
|
122
|
+
colorWhen: ['when', 'color', 'else'],
|
|
123
|
+
level: ['title', 'value', 'color', 'style'],
|
|
124
|
+
fill: ['between', 'color', 'opacity'],
|
|
125
|
+
signal: ['title', 'when', 'shape', 'position', 'color', 'text', 'size', 'alert'],
|
|
126
|
+
rule: ['title', 'when', 'color', 'opacity'],
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
130
|
+
|
|
131
|
+
function closest(name: string, names: readonly string[]): string | undefined {
|
|
132
|
+
const n = name.toLowerCase();
|
|
133
|
+
let best: string | undefined;
|
|
134
|
+
let bestD = Infinity;
|
|
135
|
+
for (const k of names) {
|
|
136
|
+
const a = n;
|
|
137
|
+
const b = k.toLowerCase();
|
|
138
|
+
const row = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
139
|
+
for (let i = 1; i <= a.length; i++) {
|
|
140
|
+
let diag = row[0]!;
|
|
141
|
+
row[0] = i;
|
|
142
|
+
for (let j = 1; j <= b.length; j++) {
|
|
143
|
+
const up = row[j]!;
|
|
144
|
+
row[j] = Math.min(up + 1, row[j - 1]! + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
145
|
+
diag = up;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (row[b.length]! < bestD) {
|
|
149
|
+
bestD = row[b.length]!;
|
|
150
|
+
best = k;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (bestD <= Math.max(2, Math.floor(name.length / 3))) return best;
|
|
154
|
+
// a longer or shorter form of a field: "minimum" for "min"
|
|
155
|
+
return names.find((k) => k.length >= 3 && (n.startsWith(k.toLowerCase()) || k.toLowerCase().startsWith(n)));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
class Checker {
|
|
159
|
+
readonly errors: string[] = [];
|
|
160
|
+
error(where: string, msg: string): void {
|
|
161
|
+
this.errors.push(`${where}: ${msg}`);
|
|
162
|
+
}
|
|
163
|
+
keys(where: string, o: Record<string, unknown>, kind: string, required: string[] = []): void {
|
|
164
|
+
for (const k of Object.keys(o)) {
|
|
165
|
+
if (KEYS[kind]!.includes(k)) continue;
|
|
166
|
+
const near = closest(k, KEYS[kind]!);
|
|
167
|
+
this.error(where, `there is no field "${k}".` + (near ? ` Did you mean "${near}"?` : '') + ` The fields are: ${KEYS[kind]!.join(', ')}.`);
|
|
168
|
+
}
|
|
169
|
+
for (const k of required) if (o[k] === undefined) this.error(where, `"${k}" is missing.`);
|
|
170
|
+
}
|
|
171
|
+
text(where: string, v: unknown, name: string): void {
|
|
172
|
+
if (v !== undefined && (typeof v !== 'string' || !v.trim())) this.error(where, `"${name}" is a text.`);
|
|
173
|
+
}
|
|
174
|
+
oneOf(where: string, v: unknown, name: string, list: readonly string[]): void {
|
|
175
|
+
if (v !== undefined && !list.includes(v as string)) this.error(where, `"${name}" is one of ${list.map((x) => `"${x}"`).join(', ')}, got ${JSON.stringify(v)}.`);
|
|
176
|
+
}
|
|
177
|
+
color(where: string, v: unknown, name: string): void {
|
|
178
|
+
if (v !== undefined && colorOf(v) === undefined) {
|
|
179
|
+
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)".`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
opacity(where: string, v: unknown): void {
|
|
183
|
+
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)}.`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const COLOR_NAMES = ['aqua', 'black', 'blue', 'fuchsia', 'gray', 'green', 'lime', 'maroon', 'navy', 'olive', 'orange', 'purple', 'red', 'silver', 'teal', 'white', 'yellow'];
|
|
188
|
+
const SHAPES = ['triangleup', 'triangledown', 'arrowup', 'arrowdown', 'circle', 'square', 'diamond', 'cross', 'xcross', 'flag', 'labelup', 'labeldown'];
|
|
189
|
+
const POSITIONS: Record<string, string> = { above: 'abovebar', below: 'belowbar', top: 'top', bottom: 'bottom' };
|
|
190
|
+
const STYLES = ['line', 'histogram', 'columns', 'area', 'circles', 'stepline', 'cross'];
|
|
191
|
+
const SOURCES = ['open', 'high', 'low', 'close', 'volume', 'hl2', 'hlc3', 'ohlc4', 'hlcc4'];
|
|
192
|
+
|
|
193
|
+
function colorOf(v: unknown): string | undefined {
|
|
194
|
+
if (typeof v !== 'string') return undefined;
|
|
195
|
+
const name = v.trim().toLowerCase();
|
|
196
|
+
if (COLOR_NAMES.includes(name)) return (color as unknown as Record<string, string>)[name];
|
|
197
|
+
return isColorText(v) ? v.trim() : undefined;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Host-side: the mistakes of an indicator in JSON, one message each ("plots[1]: "value" is missing."); empty when
|
|
202
|
+
* there are none. The formulas are checked when the indicator runs. A script does not call it.
|
|
203
|
+
* @param spec - The indicator in JSON, as parsed (an object).
|
|
204
|
+
* @returns One message per mistake.
|
|
205
|
+
*/
|
|
206
|
+
export function checkIndicatorJson(spec: unknown): string[] {
|
|
207
|
+
const c = new Checker();
|
|
208
|
+
if (!isObject(spec)) return ['the indicator is a JSON object: { "title": "...", "plots": [...] }.'];
|
|
209
|
+
c.keys('indicator', spec, 'indicator', ['title']);
|
|
210
|
+
c.text('indicator', spec.title, 'title');
|
|
211
|
+
c.text('indicator', spec.shortTitle, 'shortTitle');
|
|
212
|
+
c.oneOf('indicator', spec.pane, 'pane', ['price', 'separate', 'auto']);
|
|
213
|
+
const names = new Set<string>();
|
|
214
|
+
const name = (where: string, id: string): void => {
|
|
215
|
+
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.`);
|
|
216
|
+
if (names.has(id)) c.error(where, `the name "${id}" is used twice.`);
|
|
217
|
+
names.add(id);
|
|
218
|
+
};
|
|
219
|
+
if (spec.inputs !== undefined) {
|
|
220
|
+
if (!isObject(spec.inputs)) c.error('inputs', 'the settings are an object: { "length": 14 }.');
|
|
221
|
+
else
|
|
222
|
+
for (const [id, v] of Object.entries(spec.inputs)) {
|
|
223
|
+
const where = `inputs.${id}`;
|
|
224
|
+
name(where, id);
|
|
225
|
+
if (isObject(v)) {
|
|
226
|
+
c.keys(where, v, 'input', ['default']);
|
|
227
|
+
c.oneOf(where, v.type, 'type', ['int', 'float', 'bool', 'text', 'source', 'color']);
|
|
228
|
+
if (v.type === 'source' && !SOURCES.includes(v.default as string)) c.error(where, `a source is one of ${SOURCES.join(', ')}.`);
|
|
229
|
+
if (v.type === 'color') c.color(where, v.default, 'default');
|
|
230
|
+
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.');
|
|
231
|
+
for (const k of ['min', 'max', 'step'] as const) if (v[k] !== undefined && typeof v[k] !== 'number') c.error(where, `"${k}" is a number.`);
|
|
232
|
+
} else if (!['number', 'boolean', 'string'].includes(typeof v)) {
|
|
233
|
+
c.error(where, 'a setting is a number, true / false, a text, or { "default": ..., "title": ... }.');
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (spec.values !== undefined) {
|
|
238
|
+
if (!isObject(spec.values)) c.error('values', 'the values are an object of formulas: { "fast": "ema(close, 9)" }.');
|
|
239
|
+
else
|
|
240
|
+
for (const [id, f] of Object.entries(spec.values)) {
|
|
241
|
+
name(`values.${id}`, id);
|
|
242
|
+
c.text(`values.${id}`, f, 'formula');
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const list = (key: string, check: (where: string, o: Record<string, unknown>) => void): void => {
|
|
246
|
+
const v = spec[key];
|
|
247
|
+
if (v === undefined) return;
|
|
248
|
+
if (!Array.isArray(v)) return c.error(key, 'is a list: [ { ... }, { ... } ].');
|
|
249
|
+
v.forEach((o, k) => (isObject(o) ? check(`${key}[${k}]`, o) : c.error(`${key}[${k}]`, 'is an object { ... }.')));
|
|
250
|
+
};
|
|
251
|
+
list('plots', (w, o) => {
|
|
252
|
+
c.keys(w, o, 'plot', ['title', 'value']);
|
|
253
|
+
c.text(w, o.title, 'title');
|
|
254
|
+
c.text(w, o.value, 'value');
|
|
255
|
+
c.color(w, o.color, 'color');
|
|
256
|
+
c.oneOf(w, o.style, 'style', STYLES);
|
|
257
|
+
if (o.width !== undefined && !(typeof o.width === 'number' && o.width >= 1 && o.width <= 4)) c.error(w, '"width" is 1 to 4.');
|
|
258
|
+
if (o.colorWhen !== undefined) {
|
|
259
|
+
if (!isObject(o.colorWhen)) c.error(w, '"colorWhen" is { "when": "...", "color": "...", "else": "..." }.');
|
|
260
|
+
else {
|
|
261
|
+
c.keys(`${w}.colorWhen`, o.colorWhen, 'colorWhen', ['when', 'color']);
|
|
262
|
+
c.color(`${w}.colorWhen`, o.colorWhen.color, 'color');
|
|
263
|
+
c.color(`${w}.colorWhen`, o.colorWhen.else, 'else');
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
list('levels', (w, o) => {
|
|
268
|
+
c.keys(w, o, 'level', ['value']);
|
|
269
|
+
if (o.value !== undefined && typeof o.value !== 'number') c.error(w, '"value" is a number.');
|
|
270
|
+
c.color(w, o.color, 'color');
|
|
271
|
+
c.oneOf(w, o.style, 'style', ['solid', 'dashed', 'dotted']);
|
|
272
|
+
});
|
|
273
|
+
list('fills', (w, o) => {
|
|
274
|
+
c.keys(w, o, 'fill', ['between', 'color']);
|
|
275
|
+
if (o.between !== undefined && !(Array.isArray(o.between) && o.between.length === 2 && o.between.every((x) => typeof x === 'string'))) {
|
|
276
|
+
c.error(w, '"between" is the titles of two plots or two levels: ["Upper", "Lower"].');
|
|
277
|
+
}
|
|
278
|
+
c.color(w, o.color, 'color');
|
|
279
|
+
c.opacity(w, o.opacity);
|
|
280
|
+
});
|
|
281
|
+
list('signals', (w, o) => {
|
|
282
|
+
c.keys(w, o, 'signal', ['title', 'when']);
|
|
283
|
+
c.text(w, o.when, 'when');
|
|
284
|
+
c.oneOf(w, o.shape, 'shape', SHAPES);
|
|
285
|
+
c.oneOf(w, o.position, 'position', Object.keys(POSITIONS));
|
|
286
|
+
c.oneOf(w, o.size, 'size', ['tiny', 'small', 'normal', 'large', 'huge']);
|
|
287
|
+
c.color(w, o.color, 'color');
|
|
288
|
+
if (o.alert !== undefined && typeof o.alert !== 'boolean' && typeof o.alert !== 'string') c.error(w, '"alert" is true or the alert message.');
|
|
289
|
+
});
|
|
290
|
+
for (const key of ['background', 'barColors']) {
|
|
291
|
+
list(key, (w, o) => {
|
|
292
|
+
c.keys(w, o, 'rule', ['when', 'color']);
|
|
293
|
+
c.text(w, o.when, 'when');
|
|
294
|
+
c.color(w, o.color, 'color');
|
|
295
|
+
c.opacity(w, o.opacity);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
return c.errors;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// ── The script ───────────────────────────────────────────────────────────────
|
|
302
|
+
|
|
303
|
+
const faded = (c: string, opacity: number): string => (opacity >= 1 ? c : color.fade(c, 1 - opacity));
|
|
304
|
+
|
|
305
|
+
function declareInput(id: string, v: JsonInput): number | boolean | string | Series {
|
|
306
|
+
const o = isObject(v) ? (v as Exclude<JsonInput, number | boolean | string>) : { default: v };
|
|
307
|
+
const title = o.title ?? id;
|
|
308
|
+
const common = { id, ...(o.tooltip ? { tooltip: o.tooltip } : {}), ...(o.group ? { group: o.group } : {}) };
|
|
309
|
+
const d = o.default;
|
|
310
|
+
const type = o.type ?? (typeof d === 'boolean' ? 'bool' : typeof d === 'number' ? (Number.isInteger(d) && !(o.step && !Number.isInteger(o.step)) ? 'int' : 'float') : 'text');
|
|
311
|
+
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[] } : {}) };
|
|
312
|
+
switch (type) {
|
|
313
|
+
case 'int':
|
|
314
|
+
return input.int(d as number, title, numeric);
|
|
315
|
+
case 'float':
|
|
316
|
+
return input.float(d as number, title, numeric);
|
|
317
|
+
case 'bool':
|
|
318
|
+
return input.bool(d as boolean, title, common);
|
|
319
|
+
case 'source':
|
|
320
|
+
return input.source(d as string, title, common);
|
|
321
|
+
case 'color':
|
|
322
|
+
return input.color(colorOf(d)!, title, common);
|
|
323
|
+
default:
|
|
324
|
+
return input.string(String(d), title, { ...common, ...(o.options ? { options: o.options.map(String) } : {}) });
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Host-side: the script body of an indicator in JSON (for `executeScript`, or a host's own runner). A script does not
|
|
330
|
+
* call it.
|
|
331
|
+
* @param spec - The indicator in JSON: an object, or its text.
|
|
332
|
+
* @returns The script body. Throws on a mistake in the JSON.
|
|
333
|
+
*/
|
|
334
|
+
export function indicatorBodyFromJson(spec: IndicatorJson | string): () => void {
|
|
335
|
+
const parsed = parseSpec(spec);
|
|
336
|
+
const errors = checkIndicatorJson(parsed);
|
|
337
|
+
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- ')}`);
|
|
338
|
+
const s = parsed as IndicatorJson;
|
|
339
|
+
return () => {
|
|
340
|
+
indicator(s.title, { ...(s.shortTitle ? { shorttitle: s.shortTitle } : {}), pane: s.pane ?? 'auto' });
|
|
341
|
+
const vars: FormulaVariables = {};
|
|
342
|
+
const asVar = (v: number | boolean | string | Series): number | boolean | Series | undefined => (typeof v === 'string' ? undefined : v);
|
|
343
|
+
const texts: Record<string, string> = {};
|
|
344
|
+
for (const [id, v] of Object.entries(s.inputs ?? {})) {
|
|
345
|
+
const value = declareInput(id, v);
|
|
346
|
+
const x = asVar(value);
|
|
347
|
+
if (x !== undefined) vars[id] = x;
|
|
348
|
+
else texts[id] = value as string;
|
|
349
|
+
}
|
|
350
|
+
// a text setting is only compared in a formula (mode == "EMA"): the comparison is replaced by 1 or 0
|
|
351
|
+
const calc = (text: string, where: string): Series | number => {
|
|
352
|
+
try {
|
|
353
|
+
return evaluateFormula(withTexts(text, texts), vars);
|
|
354
|
+
} catch (err) {
|
|
355
|
+
if (err instanceof ScriptError) throw new ScriptError(`${where}: ${err.message}`);
|
|
356
|
+
throw err;
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
for (const [id, f] of Object.entries(s.values ?? {})) vars[id] = calc(f, `values.${id}`);
|
|
360
|
+
const handles = new Map<string, PlotHandle>();
|
|
361
|
+
(s.plots ?? []).forEach((p, k) => {
|
|
362
|
+
const value = calc(p.value, `plots[${k}]`);
|
|
363
|
+
const fixed = p.color !== undefined ? colorOf(p.color) : undefined;
|
|
364
|
+
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;
|
|
365
|
+
const style = p.style === 'stepline' ? 'stepline' : p.style;
|
|
366
|
+
handles.set(p.title, plot(value, p.title, { ...(perBar ? { color: perBar as string[] } : fixed ? { color: fixed } : {}), ...(p.width ? { linewidth: p.width } : {}), ...(style ? { style } : {}) }));
|
|
367
|
+
vars[slugName(p.title)] ??= value as Series;
|
|
368
|
+
});
|
|
369
|
+
(s.levels ?? []).forEach((l) => {
|
|
370
|
+
const title = l.title ?? String(l.value);
|
|
371
|
+
handles.set(title, hline(l.value, title, { ...(l.color ? { color: colorOf(l.color) } : {}), ...(l.style ? { linestyle: l.style } : {}) }));
|
|
372
|
+
});
|
|
373
|
+
(s.fills ?? []).forEach((f, k) => {
|
|
374
|
+
const [a, b] = f.between.map((t) => {
|
|
375
|
+
const h = handles.get(t);
|
|
376
|
+
if (!h) throw new ScriptError(`fills[${k}]: there is no plot or level titled "${t}". The titles are: ${[...handles.keys()].join(', ')}.`);
|
|
377
|
+
return h;
|
|
378
|
+
});
|
|
379
|
+
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.`);
|
|
380
|
+
fill(a!, b!, { color: faded(colorOf(f.color)!, f.opacity ?? 0.15) });
|
|
381
|
+
});
|
|
382
|
+
(s.signals ?? []).forEach((g, k) => {
|
|
383
|
+
const when = asSeriesOf(calc(g.when, `signals[${k}]`));
|
|
384
|
+
const position = POSITIONS[g.position ?? 'below']!;
|
|
385
|
+
const shape = g.shape ?? (position === 'abovebar' || position === 'top' ? 'triangledown' : 'triangleup');
|
|
386
|
+
plotshape(when, g.title, {
|
|
387
|
+
style: shape as never,
|
|
388
|
+
location: position as never,
|
|
389
|
+
...(g.color ? { color: colorOf(g.color) } : {}),
|
|
390
|
+
...(g.text ? { text: g.text } : {}),
|
|
391
|
+
...(g.size ? { size: g.size as never } : {}),
|
|
392
|
+
});
|
|
393
|
+
if (g.alert) alertcondition(when, g.title, typeof g.alert === 'string' ? g.alert : g.title);
|
|
394
|
+
});
|
|
395
|
+
(s.background ?? []).forEach((r, k) => {
|
|
396
|
+
bgcolor(color.when(asSeriesOf(calc(r.when, `background[${k}]`)), faded(colorOf(r.color)!, r.opacity ?? 0.15)), { ...(r.title ? { title: r.title } : {}) });
|
|
397
|
+
});
|
|
398
|
+
(s.barColors ?? []).forEach((r, k) => {
|
|
399
|
+
barcolor(color.when(asSeriesOf(calc(r.when, `barColors[${k}]`)), faded(colorOf(r.color)!, r.opacity ?? 1)), { ...(r.title ? { title: r.title } : {}) });
|
|
400
|
+
});
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** A plot title as a formula name: "Fast MA" gives fast_ma. */
|
|
405
|
+
const slugName = (title: string): string => title.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').replace(/^(\d)/, '_$1') || 'plot';
|
|
406
|
+
|
|
407
|
+
/** A condition that gives a number (no Series used) as a Series. */
|
|
408
|
+
function asSeriesOf(v: Series | number): Series {
|
|
409
|
+
return typeof v === 'number' ? Series.constant(close.barData, v) : v;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** A text setting compared in a formula (`mode == "EMA"`): the comparison becomes 1 or 0. */
|
|
413
|
+
function withTexts(text: string, texts: Record<string, string>): string {
|
|
414
|
+
return text.replace(/\b([A-Za-z_]\w*)\s*(==|!=|=)\s*"([^"]*)"/g, (all, id: string, op: string, value: string) => {
|
|
415
|
+
if (!(id in texts)) return all;
|
|
416
|
+
const same = texts[id] === value;
|
|
417
|
+
return op === '!=' ? (same ? '0' : '1') : same ? '1' : '0';
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function parseSpec(spec: IndicatorJson | string): unknown {
|
|
422
|
+
if (typeof spec !== 'string') return spec;
|
|
423
|
+
try {
|
|
424
|
+
return JSON.parse(spec);
|
|
425
|
+
} catch (err) {
|
|
426
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
427
|
+
const pos = /position (\d+)/.exec(msg);
|
|
428
|
+
let where = '';
|
|
429
|
+
if (pos) {
|
|
430
|
+
const before = spec.slice(0, Number(pos[1]));
|
|
431
|
+
where = ` (line ${before.split('\n').length}, column ${before.length - before.lastIndexOf('\n')})`;
|
|
432
|
+
}
|
|
433
|
+
throw new ScriptError(`The indicator is not valid JSON${where}: ${msg}. Check the commas between fields and the double quotes around names and texts.`);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Host-side: an indicator described in JSON (an object or its text), ready to use: the same as `defineIndicator` of
|
|
439
|
+
* its script. A script does not call it.
|
|
440
|
+
*
|
|
441
|
+
* ```js
|
|
442
|
+
* const cross = defineIndicatorFromJson({
|
|
443
|
+
* title: 'Average cross',
|
|
444
|
+
* inputs: { fast: 9, slow: 21 },
|
|
445
|
+
* values: { fastLine: 'ema(close, fast)', slowLine: 'ema(close, slow)' },
|
|
446
|
+
* plots: [{ title: 'Fast', value: 'fastLine', color: 'teal' }, { title: 'Slow', value: 'slowLine', color: 'orange' }],
|
|
447
|
+
* signals: [{ title: 'Buy', when: 'crossover(fastLine, slowLine)', position: 'below', color: 'green', alert: true }],
|
|
448
|
+
* });
|
|
449
|
+
* cross.calculate(bars, { fast: 5 });
|
|
450
|
+
* ```
|
|
451
|
+
* @param spec - The indicator in JSON: an object, or its text.
|
|
452
|
+
* @param options - Strict mode and the other run options. Default: `{}`.
|
|
453
|
+
* @returns The indicator, as `defineIndicator` gives it. Throws on a mistake in the JSON.
|
|
454
|
+
*/
|
|
455
|
+
export function defineIndicatorFromJson(spec: IndicatorJson | string, options: DefineIndicatorOptions = {}): IndicatorDefinition {
|
|
456
|
+
return defineIndicator(indicatorBodyFromJson(spec), options);
|
|
457
|
+
}
|
package/src/security/other.ts
CHANGED
|
@@ -21,6 +21,12 @@
|
|
|
21
21
|
* lookahead on (the open 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
|
|
@@ -133,6 +139,7 @@ function closeTimes(times: number[], tf: string, zone: Zone | null): number[] {
|
|
|
133
139
|
const calendar = calendarOf(zone, tf);
|
|
134
140
|
const info = timeframe.info(tf);
|
|
135
141
|
const len = timeframe.in_seconds(tf) * 1000;
|
|
142
|
+
if (info.isticks) return times.map((_, i) => (i + 1 < times.length ? times[i + 1]! : Infinity));
|
|
136
143
|
return times.map((t, i) => {
|
|
137
144
|
if (calendar) {
|
|
138
145
|
const c = periodClose(t, tf, calendar);
|
|
@@ -167,6 +174,16 @@ function latestAtOrBefore(keys: number[], at: number[]): number[] {
|
|
|
167
174
|
});
|
|
168
175
|
}
|
|
169
176
|
|
|
177
|
+
/** For each element of `at` (non-decreasing), the index of the first element of `keys` (non-decreasing) >= it;
|
|
178
|
+
* `keys.length`: none. */
|
|
179
|
+
function firstAtOrAfter(keys: number[], at: number[]): number[] {
|
|
180
|
+
let j = 0;
|
|
181
|
+
return at.map((x) => {
|
|
182
|
+
while (j < keys.length && keys[j]! < x) j++;
|
|
183
|
+
return j;
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
170
187
|
const zoneOf = (c: SymbolCalendar | undefined): Zone | null =>
|
|
171
188
|
c?.timezone && c.session ? { timezone: c.timezone, session: c.session } : null;
|
|
172
189
|
|
|
@@ -180,7 +197,6 @@ function setup(
|
|
|
180
197
|
): { chartTf: string; otherTf: string; chartZone: Zone | null; otherZone: Zone | null } {
|
|
181
198
|
const chartTf = timeframe.info(chart.timeframe).period;
|
|
182
199
|
const otherTf = tf.trim() === '' ? chartTf : timeframe.info(tf).period;
|
|
183
|
-
if (timeframe.info(otherTf).isticks) throw new RangeError(`request.security: tick timeframe "${tf}" is not supported.`);
|
|
184
200
|
const chartZone = zoneOf(chart) ?? (tradesEveryDay(ct, chartTf) ? UTC_24X7 : null);
|
|
185
201
|
const otherZone =
|
|
186
202
|
zoneOf(options.other) ??
|
|
@@ -193,8 +209,7 @@ function setup(
|
|
|
193
209
|
* for na (#179). `otherBars` are the bars of the other symbol on `tf` ("" for the chart timeframe, or a higher
|
|
194
210
|
* or a lower one), with times in the unit of the chart bars. Rules in the module notes; the same rules hold for a
|
|
195
211
|
* lower timeframe (#181): lookahead off shows the last lower bar that closes by the close of the chart bar, lookahead
|
|
196
|
-
* on the last one that opened by its open. It also serves the chart symbol on a lower timeframe.
|
|
197
|
-
* @throws RangeError for a tick timeframe
|
|
212
|
+
* on the last one that opened by its open. It also serves the chart symbol on a lower timeframe, and ticks (#214).
|
|
198
213
|
*/
|
|
199
214
|
export function securityOther(
|
|
200
215
|
chartBars: ReadonlyArray<{ time: number }>,
|
|
@@ -226,7 +241,17 @@ export function securityOther(
|
|
|
226
241
|
on = latestAtOrBefore(ot, ct);
|
|
227
242
|
}
|
|
228
243
|
}
|
|
229
|
-
const
|
|
244
|
+
const chartClose = closeTimes(ct, chartTf, chartZone);
|
|
245
|
+
// ticks: the last tick bar that opened before the chart bar's close; on a tick chart, the bars that closed before
|
|
246
|
+
// the next tick bar opened
|
|
247
|
+
const before = (keys: number[]) => firstAtOrAfter(keys, chartClose).map((j) => j - 1);
|
|
248
|
+
const index = options.lookahead
|
|
249
|
+
? on
|
|
250
|
+
: timeframe.info(otherTf).isticks
|
|
251
|
+
? before(ot)
|
|
252
|
+
: timeframe.info(chartTf).isticks
|
|
253
|
+
? before(closeTimes(ot, otherTf, otherZone))
|
|
254
|
+
: latestAtOrBefore(closeTimes(ot, otherTf, otherZone), chartClose);
|
|
230
255
|
// realtime updates of the open last bar: lookahead off shows the bar of lookahead on
|
|
231
256
|
if (realtime) index[n - 1] = on[n - 1]!;
|
|
232
257
|
if (!options.gaps) return index;
|
|
@@ -237,7 +262,7 @@ export function securityOther(
|
|
|
237
262
|
* PineScript `request.security_lower_tf` (#181): for each chart bar, the range `[from, to)` of the bars of
|
|
238
263
|
* `otherBars` (a lower timeframe, the chart symbol or another one) that it contains: the bars whose close time is
|
|
239
264
|
* 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
|
|
240
|
-
* day, which closes at 20:00). An empty range for a chart bar without such bars.
|
|
265
|
+
* day, which closes at 20:00); tick bars by their open time (#214). An empty range for a chart bar without such bars.
|
|
241
266
|
*
|
|
242
267
|
* As PineScript, at most the last {@link MAX_INTRABARS} (100,000) lower-timeframe bars are given out
|
|
243
268
|
* (`options.maxIntrabars` changes it): the older chart bars get an empty range (#192).
|
|
@@ -253,10 +278,19 @@ export function securityLowerTf(
|
|
|
253
278
|
const ct = chartBars.map((b) => b.time * unit);
|
|
254
279
|
const ot = otherBars.map((b) => b.time * unit);
|
|
255
280
|
const { chartTf, otherTf, chartZone, otherZone } = setup(ct, ot, tf, chart, options);
|
|
256
|
-
const
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
281
|
+
const chartClose = closeTimes(ct, chartTf, chartZone);
|
|
282
|
+
let ranges: Array<[number, number]>;
|
|
283
|
+
if (timeframe.info(otherTf).isticks) {
|
|
284
|
+
// tick bars by their open time: at or after the chart bar's open, before its close (#214)
|
|
285
|
+
const from = firstAtOrAfter(ot, ct);
|
|
286
|
+
const to = firstAtOrAfter(ot, chartClose);
|
|
287
|
+
ranges = ct.map((_, i): [number, number] => [from[i]!, Math.max(from[i]!, to[i]!)]);
|
|
288
|
+
} else {
|
|
289
|
+
const oc = closeTimes(ot, otherTf, otherZone);
|
|
290
|
+
const from = latestAtOrBefore(oc, ct);
|
|
291
|
+
const to = latestAtOrBefore(oc, chartClose);
|
|
292
|
+
ranges = ct.map((_, i): [number, number] => [from[i]! + 1, Math.max(from[i]! + 1, to[i]! + 1)]);
|
|
293
|
+
}
|
|
260
294
|
// the last `max` intrabars of the chart bars: the ones before are not given
|
|
261
295
|
const max = options.maxIntrabars ?? MAX_INTRABARS;
|
|
262
296
|
const end = ranges.reduce((m, [, t]) => Math.max(m, t), 0);
|