oakscriptjs 0.24.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 +530 -60
- 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/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 +1096 -151
- 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/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/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 +1517 -239
- package/src/script/json.ts +457 -0
- 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
package/dist/esm/script/index.js
CHANGED
|
@@ -40,7 +40,8 @@ import { outerWrites } from './closure-writes.js';
|
|
|
40
40
|
import * as pineConstants from './constants.js';
|
|
41
41
|
import { drawingNamespace, isPlainObject, namedArguments, unknownArgument } from './drawing-args.js';
|
|
42
42
|
import * as colorCore from '../color/index.js';
|
|
43
|
-
import
|
|
43
|
+
import * as compareCore from '../compare/index.js';
|
|
44
|
+
import { inputColorDefault, isColorText } from '../color/parse.js';
|
|
44
45
|
import { fixnan as fixnanValues, isNA, nz as nzValue } from '../utils/index.js';
|
|
45
46
|
import { externalSource } from '../utils/source-resolver.js';
|
|
46
47
|
import * as lineCore from '../line/index.js';
|
|
@@ -52,13 +53,25 @@ import * as tableCore from '../table/index.js';
|
|
|
52
53
|
import * as chartPointCore from '../chartpoint/index.js';
|
|
53
54
|
import * as textCore from '../text/index.js';
|
|
54
55
|
import * as mathCore from '../math/index.js';
|
|
55
|
-
import { createdDrawingKinds, resetDrawings, restoreDrawingCheckpoint, restoreDrawingState, saveDrawingCheckpoint, saveDrawingState, setDrawingBar, setDrawingLimits, holdDrawing, releaseDrawing, } from '../drawing/registry.js';
|
|
56
|
+
import { createdDrawingKinds, droppedDrawings, resetDrawings, restoreDrawingCheckpoint, restoreDrawingState, saveDrawingCheckpoint, saveDrawingState, setDrawingBar, setDrawingLimits, holdDrawing, releaseDrawing, } from '../drawing/registry.js';
|
|
56
57
|
export { holdDrawing, releaseDrawing } from '../drawing/registry.js';
|
|
57
58
|
/**
|
|
58
|
-
* A
|
|
59
|
-
*
|
|
60
|
-
*
|
|
59
|
+
* A variable that holds one drawing (a line, label, box...) from bar to bar and keeps it alive: the object it holds is
|
|
60
|
+
* never deleted by the `max_*_count` limit of the script. Use it to create one object and move it, instead of a new
|
|
61
|
+
* object on each bar. Assigning another object (or `undefined` for na) releases the one before, which the limit can
|
|
62
|
+
* delete again. Declare it in the script body (outside the bar loops), then read and write `.value` in a bar loop.
|
|
63
|
+
* @param initial - The object held from the start. Default: none (`.value` is `undefined`).
|
|
64
|
+
* @returns A box whose `.value` is the held object, or `undefined`.
|
|
65
|
+
* @example
|
|
66
|
+
* ```js
|
|
67
|
+
* const level = varDrawing();
|
|
68
|
+
* eachBar((c) => {
|
|
69
|
+
* if (c.i === c.n - 1) level.value = line.new(c.i - 20, c.close, c.i, c.close, { color: color.orange });
|
|
70
|
+
* });
|
|
71
|
+
* ```
|
|
61
72
|
*/
|
|
73
|
+
// Without an initial object the kind is not known: `.value` is any drawing, so `line.delete(v.value)` checks.
|
|
74
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
62
75
|
export function varDrawing(initial) {
|
|
63
76
|
const box = persist(initial ? holdDrawing(initial) : undefined);
|
|
64
77
|
return {
|
|
@@ -99,8 +112,9 @@ function collector() {
|
|
|
99
112
|
}
|
|
100
113
|
return ctx;
|
|
101
114
|
}
|
|
102
|
-
function freshCollector(inputValues) {
|
|
115
|
+
function freshCollector(inputValues, strict = false) {
|
|
103
116
|
return {
|
|
117
|
+
strict,
|
|
104
118
|
title: 'Untitled',
|
|
105
119
|
overlay: false,
|
|
106
120
|
inputValues,
|
|
@@ -144,6 +158,174 @@ function slugId(title, fallback, taken) {
|
|
|
144
158
|
taken.add(id);
|
|
145
159
|
return id;
|
|
146
160
|
}
|
|
161
|
+
/** A value as it is written in a script, for messages. */
|
|
162
|
+
function shown(v) {
|
|
163
|
+
if (typeof v === 'string')
|
|
164
|
+
return JSON.stringify(v);
|
|
165
|
+
if (typeof v === 'number' || typeof v === 'boolean' || v === null || v === undefined)
|
|
166
|
+
return String(v);
|
|
167
|
+
return Array.isArray(v) ? 'a list' : typeof v === 'object' ? 'an object' : typeof v;
|
|
168
|
+
}
|
|
169
|
+
/** Up to three of `names` close to `name` (spelling mistakes), closest first. */
|
|
170
|
+
function closeNames(name, names) {
|
|
171
|
+
const bare = (x) => x.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
172
|
+
const same = names.filter((k) => bare(k) === bare(name));
|
|
173
|
+
if (same.length)
|
|
174
|
+
return same;
|
|
175
|
+
const n = name.toLowerCase();
|
|
176
|
+
const dist = (a, b) => {
|
|
177
|
+
const row = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
178
|
+
for (let i = 1; i <= a.length; i++) {
|
|
179
|
+
let diag = row[0];
|
|
180
|
+
row[0] = i;
|
|
181
|
+
for (let j = 1; j <= b.length; j++) {
|
|
182
|
+
const up = row[j];
|
|
183
|
+
row[j] = Math.min(up + 1, row[j - 1] + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
184
|
+
diag = up;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return row[b.length];
|
|
188
|
+
};
|
|
189
|
+
return names
|
|
190
|
+
.map((k) => ({ k, d: dist(n, k.toLowerCase()) }))
|
|
191
|
+
.filter(({ k, d }) => d <= Math.max(2, Math.floor(name.length / 3)) || k.toLowerCase().includes(n) || n.includes(k.toLowerCase()))
|
|
192
|
+
.sort((a, b) => a.d - b.d)
|
|
193
|
+
.slice(0, 3)
|
|
194
|
+
.map(({ k }) => k);
|
|
195
|
+
}
|
|
196
|
+
/** Strict mode: every input value given by the host has a name the script declares. */
|
|
197
|
+
function checkInputNames(c, inputs) {
|
|
198
|
+
const names = c.inputConfig.map((i) => i.id);
|
|
199
|
+
for (const key of Object.keys(inputs)) {
|
|
200
|
+
if (c.inputIds.has(key))
|
|
201
|
+
continue;
|
|
202
|
+
const near = closeNames(key, names);
|
|
203
|
+
throw new ScriptError(`There is no input "${key}".` + (near.length ? ` Did you mean "${near.join('", "')}"?` : '') +
|
|
204
|
+
(names.length ? ` The inputs are: ${names.join(', ')}.` : ' The script has no inputs.'));
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
/** Strict mode: the value the host gives an input has its type, range and options. */
|
|
208
|
+
function checkInputValue(config, id, value) {
|
|
209
|
+
const name = config.title ? `"${config.title}" (${id})` : `"${id}"`;
|
|
210
|
+
const fail = (why) => {
|
|
211
|
+
throw new ScriptError(`Input ${name}: ${why}`);
|
|
212
|
+
};
|
|
213
|
+
switch (config.type) {
|
|
214
|
+
case 'int':
|
|
215
|
+
case 'float':
|
|
216
|
+
case 'price':
|
|
217
|
+
case 'time':
|
|
218
|
+
if (typeof value !== 'number' || Number.isNaN(value))
|
|
219
|
+
fail(`${shown(value)} is not a number.`);
|
|
220
|
+
if (config.type === 'int' && !Number.isInteger(value))
|
|
221
|
+
fail(`${value} is not a whole number.`);
|
|
222
|
+
if (config.min !== undefined && value < config.min)
|
|
223
|
+
fail(`${value} is below the minimum, ${config.min}.`);
|
|
224
|
+
if (config.max !== undefined && value > config.max)
|
|
225
|
+
fail(`${value} is above the maximum, ${config.max}.`);
|
|
226
|
+
break;
|
|
227
|
+
case 'bool':
|
|
228
|
+
if (typeof value !== 'boolean')
|
|
229
|
+
fail(`${shown(value)} is not true or false.`);
|
|
230
|
+
break;
|
|
231
|
+
case 'color':
|
|
232
|
+
if (!isColorText(value))
|
|
233
|
+
fail(`${shown(value)} is not a colour. Write it as "#ff0000" or "rgba(255, 0, 0, 0.5)".`);
|
|
234
|
+
break;
|
|
235
|
+
case 'source':
|
|
236
|
+
if (typeof value !== 'string' || (!SOURCES[value] && !externalSource(value))) {
|
|
237
|
+
fail(`${shown(value)} is not a price source. The sources are: ${Object.keys(SOURCES).join(', ')}.`);
|
|
238
|
+
}
|
|
239
|
+
break;
|
|
240
|
+
default:
|
|
241
|
+
if (typeof value !== 'string')
|
|
242
|
+
fail(`${shown(value)} is not a text.`);
|
|
243
|
+
}
|
|
244
|
+
if (config.options && !config.options.includes(value)) {
|
|
245
|
+
fail(`${shown(value)} is not one of the choices: ${config.options.map(shown).join(', ')}.`);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/** Strict mode: the named options of a declaration call are known and its colours are colours. */
|
|
249
|
+
function checkOptions(fn, options, keys, colorKeys = ['color']) {
|
|
250
|
+
if (!ctx?.strict || options === undefined)
|
|
251
|
+
return;
|
|
252
|
+
if (!isPlainObject(options))
|
|
253
|
+
throw new ScriptError(`${fn}(): the options are an object, e.g. { color: color.red }.`);
|
|
254
|
+
for (const [key, v] of Object.entries(options)) {
|
|
255
|
+
if (!keys.includes(key)) {
|
|
256
|
+
const near = closeNames(key, keys);
|
|
257
|
+
throw new ScriptError(`${fn}(): there is no option "${key}".` + (near.length ? ` Did you mean "${near.join('", "')}"?` : '') +
|
|
258
|
+
` The options are: ${keys.join(', ')}.`);
|
|
259
|
+
}
|
|
260
|
+
if (colorKeys.includes(key))
|
|
261
|
+
checkColor(`${fn}(): the ${key}`, v);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/** Strict mode: a colour argument (a colour or per-bar colours; na entries are allowed) holds colours only. */
|
|
265
|
+
function checkColor(what, v) {
|
|
266
|
+
if (v === undefined || v === null)
|
|
267
|
+
return;
|
|
268
|
+
const bad = Array.isArray(v) ? v.find((x) => x !== undefined && x !== null && x !== '' && !isColorText(x)) : isColorText(v) ? undefined : v;
|
|
269
|
+
if (bad !== undefined) {
|
|
270
|
+
const name = typeof bad === 'string' ? bad.trim().toLowerCase() : '';
|
|
271
|
+
if (/^[a-z]+$/.test(name) && typeof colorCore[name] === 'string') {
|
|
272
|
+
throw new ScriptError(`${what} ${shown(bad)} is a colour name: write color.${name} (without quotes).`);
|
|
273
|
+
}
|
|
274
|
+
throw new ScriptError(`${what} ${shown(bad)} is not a colour. Write a colour as color.red, "#ff0000" or "rgba(255, 0, 0, 0.5)".`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
/** The warnings of the run that ends (see `ScriptRunResult.warnings`). */
|
|
278
|
+
function runWarnings() {
|
|
279
|
+
const out = [];
|
|
280
|
+
const option = { line: 'max_lines_count', label: 'max_labels_count', box: 'max_boxes_count', polyline: 'max_polylines_count', linefill: 'max_lines_count' };
|
|
281
|
+
for (const [kind, n] of Object.entries(droppedDrawings())) {
|
|
282
|
+
if (!n || kind === 'table')
|
|
283
|
+
continue;
|
|
284
|
+
out.push(`${n} ${kind}${n > 1 ? 's were' : ' was'} deleted because the script made more than the maximum number of ${kind}s; ` +
|
|
285
|
+
`the oldest go first. To keep more, raise ${option[kind]} in indicator(), e.g. indicator("...", { ${option[kind]}: 500 }).`);
|
|
286
|
+
}
|
|
287
|
+
return out;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* indicator(..., { pane: 'auto' }): the plots belong on the price chart when nine values in ten (all plots together) are
|
|
291
|
+
* within the price range of the bars, widened by a quarter on each side (plots with display 'none' do not count); a script
|
|
292
|
+
* without plots goes on the price chart.
|
|
293
|
+
*/
|
|
294
|
+
function plotsOnPrices(c) {
|
|
295
|
+
const b = ctxBars.bars;
|
|
296
|
+
let lo = Infinity;
|
|
297
|
+
let hi = -Infinity;
|
|
298
|
+
for (const bar of b) {
|
|
299
|
+
if (bar.low < lo)
|
|
300
|
+
lo = bar.low;
|
|
301
|
+
if (bar.high > hi)
|
|
302
|
+
hi = bar.high;
|
|
303
|
+
}
|
|
304
|
+
if (!(hi >= lo))
|
|
305
|
+
return true;
|
|
306
|
+
const margin = (hi - lo) * 0.25;
|
|
307
|
+
let inside = 0;
|
|
308
|
+
let total = 0;
|
|
309
|
+
// the plots shown on the chart only (display 'none': values for alerts or other scripts)
|
|
310
|
+
const shown = c.plotConfig.filter((p) => p.display !== 'none').map((p) => c.plots[p.id] ?? []);
|
|
311
|
+
for (const points of shown) {
|
|
312
|
+
for (const p of points) {
|
|
313
|
+
total++;
|
|
314
|
+
if (p.value >= lo - margin && p.value <= hi + margin)
|
|
315
|
+
inside++;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return total === 0 || inside >= total * 0.9;
|
|
319
|
+
}
|
|
320
|
+
/** The colours given in turn to plots without a colour when `ScriptOptions.palette` is true. */
|
|
321
|
+
export const DEFAULT_PALETTE = ['#2962FF', '#FF6D00', '#00897B', '#AB47BC', '#F23645', '#43A047', '#FBC02D', '#8D6E63'];
|
|
322
|
+
/** A mistake found in strict mode (see `ScriptOptions.strict`): the message says what to change. */
|
|
323
|
+
export class ScriptError extends Error {
|
|
324
|
+
constructor(message) {
|
|
325
|
+
super(message);
|
|
326
|
+
this.name = 'ScriptError';
|
|
327
|
+
}
|
|
328
|
+
}
|
|
147
329
|
let scriptOptions = {};
|
|
148
330
|
/** The `varip` values of a replayed bar in a script without `varip`. */
|
|
149
331
|
const NO_VARIP = [];
|
|
@@ -221,7 +403,7 @@ function runBody(body, barsInput, inputs, chart, options, inc) {
|
|
|
221
403
|
chartCtx = { ...chart };
|
|
222
404
|
runNow = chart.now ?? Date.now();
|
|
223
405
|
scriptOptions = options;
|
|
224
|
-
ctx = freshCollector(inputs);
|
|
406
|
+
ctx = freshCollector(inputs, options.strict === true);
|
|
225
407
|
intrabarRun = null;
|
|
226
408
|
varipRun = { slot: 0, recorder: options.recorder ?? null, mode: 'live', scratch: null };
|
|
227
409
|
currentBar = -1;
|
|
@@ -241,6 +423,10 @@ function runBody(body, barsInput, inputs, chart, options, inc) {
|
|
|
241
423
|
}
|
|
242
424
|
if (missingSymbols.length)
|
|
243
425
|
throw new MissingSymbolDataError(missingSymbols);
|
|
426
|
+
if (ctx.strict)
|
|
427
|
+
checkInputNames(ctx, inputs);
|
|
428
|
+
if (ctx.paneAuto)
|
|
429
|
+
ctx.overlay = plotsOnPrices(ctx);
|
|
244
430
|
// the outputs read the drawings: not a drawing of the script
|
|
245
431
|
if (inc)
|
|
246
432
|
incremental.bodyDone();
|
|
@@ -253,6 +439,7 @@ function runBody(body, barsInput, inputs, chart, options, inc) {
|
|
|
253
439
|
precision: c.precision,
|
|
254
440
|
format: c.format,
|
|
255
441
|
...(c.scale ? { scale: c.scale } : {}),
|
|
442
|
+
...(c.pane ? { pane: c.pane } : {}),
|
|
256
443
|
},
|
|
257
444
|
inputConfig: c.inputConfig,
|
|
258
445
|
plotConfig: c.plotConfig,
|
|
@@ -286,6 +473,7 @@ function runBody(body, barsInput, inputs, chart, options, inc) {
|
|
|
286
473
|
},
|
|
287
474
|
hasAlertFunction: c.hasAlertFunction,
|
|
288
475
|
usesVisibleRange: c.usesVisibleRange,
|
|
476
|
+
warnings: runWarnings(),
|
|
289
477
|
};
|
|
290
478
|
}
|
|
291
479
|
finally {
|
|
@@ -336,23 +524,28 @@ function setVarip(recorder, values) {
|
|
|
336
524
|
recorder.varip.push(...values);
|
|
337
525
|
}
|
|
338
526
|
/**
|
|
339
|
-
*
|
|
340
|
-
*
|
|
341
|
-
* the tick price, its high and low the extremes reached so far). The script's variables come back to
|
|
342
|
-
* the start of the bar
|
|
343
|
-
*
|
|
344
|
-
*
|
|
345
|
-
*
|
|
346
|
-
*
|
|
347
|
-
*
|
|
527
|
+
* Host-side: runs a strategy once more on one bar, inside the bar (calculation on order fills, or on the ticks of
|
|
528
|
+
* history bars). Scripts never call it. `bars` holds the bars up to that bar, the last one as it stands at the tick
|
|
529
|
+
* (its close is the tick price, its high and low the extremes reached so far). The script's variables come back to
|
|
530
|
+
* their state at the start of the bar, except `varip` ones. In strategy.eachBar(), the bars before replay the engine's
|
|
531
|
+
* answers that the main run recorded (their order calls are dropped), and the bar itself calls `options.engine`
|
|
532
|
+
* without processBar / processClose (the host is filling its orders). That bar is a confirmed history bar
|
|
533
|
+
* (`barstate.isconfirmed`); `barstate.islast`, `last_bar_index` and `BarContext.n` keep the chart's last bar. Risk
|
|
534
|
+
* rules are not declared again, and the outputs (plots, drawings) are dropped. Re-entrant: the host calls it inside
|
|
535
|
+
* the bar loop of the main run.
|
|
348
536
|
*
|
|
349
|
-
* Resumed runs
|
|
350
|
-
*
|
|
351
|
-
*
|
|
352
|
-
*
|
|
353
|
-
*
|
|
354
|
-
*
|
|
355
|
-
*
|
|
537
|
+
* Resumed runs: the intrabar runs of a backtest (same recorder, script, inputs, chart and engine) keep the state of
|
|
538
|
+
* the script as createScriptRun does, so a run calculates its bar only (and the bars since the previous intrabar run);
|
|
539
|
+
* the order calls and `strategy.*` reads are the same as in a full run. The bars before `options.bar` must be the main
|
|
540
|
+
* run's (the same on every call). A script that keeps state outside `persist()` boxes, or uses a feature that is not
|
|
541
|
+
* resumed, gets full runs (`fullRunReason`); the first resumed runs are also calculated in full and compared
|
|
542
|
+
* (`verify`). A resumed run gives its order calls to the engine once it has ended.
|
|
543
|
+
* @param body - The script body, as given to executeScript().
|
|
544
|
+
* @param bars - The bars up to and including the bar calculated inside, oldest first.
|
|
545
|
+
* @param inputs - Input values by input id, as given to the main run.
|
|
546
|
+
* @param chart - The chart context of the main run.
|
|
547
|
+
* @param options - The bar, the chart's last bar index, the main run's engine and recorder, and the resume settings.
|
|
548
|
+
* @returns The first bar calculated, whether the run was resumed, and why the runs are full ones (or null).
|
|
356
549
|
*/
|
|
357
550
|
export function executeIntrabar(body, bars, inputs, chart, options) {
|
|
358
551
|
const recorder = options.recorder;
|
|
@@ -538,7 +731,8 @@ function sameResult(a, b) {
|
|
|
538
731
|
return true;
|
|
539
732
|
}
|
|
540
733
|
/**
|
|
541
|
-
*
|
|
734
|
+
* Host-side: a script that calculates only the newest bars on a live update. Scripts never call it. The first
|
|
735
|
+
* update is a full run; it keeps,
|
|
542
736
|
* for the next one, what the script created (its Series, ta.* calls, eachBar() blocks, persist() boxes and plots) with
|
|
543
737
|
* their state at the end of the last confirmed bar. An update whose bars are the same up to the forming bar of the
|
|
544
738
|
* previous update (a new price of the forming bar, or new bars after it) runs the script again from that bar only;
|
|
@@ -550,6 +744,13 @@ function sameResult(a, b) {
|
|
|
550
744
|
* compared (`verify`): a difference makes the next updates full runs. Not resumed yet, so calculated in full: drawings,
|
|
551
745
|
* request.security, strategies, varip, timenow, last_bar_index, BarContext.n, barstate.islastconfirmedhistory
|
|
552
746
|
* (`fullRunReason` names the first one met).
|
|
747
|
+
* @param body - The script body, a function that runs the script's statements.
|
|
748
|
+
* @param inputs - Input values by input id. Default: `{}` (every input at its default).
|
|
749
|
+
* @param chart - The chart context (timeframe, time zone, session, symbol...); an update can give a new one.
|
|
750
|
+
* Default: `{}`.
|
|
751
|
+
* @param options - The executeScript() options, plus `verify` (resumed updates also run in full and compared).
|
|
752
|
+
* Default: `{}`.
|
|
753
|
+
* @returns A run: call `update(bars, chart?)` on each change of the bars; `fullRunReason` says why it does not resume.
|
|
553
754
|
*/
|
|
554
755
|
export function createScriptRun(body, inputs = {}, chart = {}, options = {}) {
|
|
555
756
|
let memory = null;
|
|
@@ -632,10 +833,19 @@ export function createScriptRun(body, inputs = {}, chart = {}, options = {}) {
|
|
|
632
833
|
}
|
|
633
834
|
let varipRun = { slot: 0, recorder: null, mode: 'live', scratch: null };
|
|
634
835
|
/**
|
|
635
|
-
*
|
|
636
|
-
*
|
|
637
|
-
*
|
|
638
|
-
*
|
|
836
|
+
* A strategy variable that keeps the changes made while a bar is calculated again inside the bar (on order fills or
|
|
837
|
+
* ticks). A plain variable comes back to its value at the start of the bar on each of those runs; a `varip` one does
|
|
838
|
+
* not, so it can count fills or ticks. Declare it once in the script body (outside the callbacks), in the same order
|
|
839
|
+
* on each run; read and write `.value` in strategy.eachBar(). Without intrabar runs it is a plain variable.
|
|
840
|
+
* @param initial - The starting value.
|
|
841
|
+
* @returns A box whose `.value` reads and writes the variable.
|
|
842
|
+
* @example
|
|
843
|
+
* ```js
|
|
844
|
+
* const updatesInTrade = varip(0);
|
|
845
|
+
* strategy.eachBar((c) => {
|
|
846
|
+
* if (strategy.position_size !== 0) updatesInTrade.value += 1;
|
|
847
|
+
* });
|
|
848
|
+
* ```
|
|
639
849
|
*/
|
|
640
850
|
export function varip(initial) {
|
|
641
851
|
collector();
|
|
@@ -674,18 +884,18 @@ export function varip(initial) {
|
|
|
674
884
|
};
|
|
675
885
|
}
|
|
676
886
|
/**
|
|
677
|
-
*
|
|
678
|
-
*
|
|
679
|
-
*
|
|
680
|
-
*
|
|
681
|
-
*
|
|
682
|
-
*
|
|
683
|
-
*
|
|
684
|
-
*
|
|
685
|
-
*
|
|
686
|
-
*
|
|
687
|
-
* ```
|
|
688
|
-
* const dir = persist(0);
|
|
887
|
+
* A variable that keeps its value from one bar to the next, kept by the runtime. Declare it in the script body
|
|
888
|
+
* (outside the callbacks), in the same order on each run, and read and write `.value` in one eachBar() callback. On a
|
|
889
|
+
* live chart the runtime saves its value at the end of the last confirmed bar and puts it back before the forming bar
|
|
890
|
+
* is calculated again, so only the newest bar is calculated: prefer it to a `let` variable outside the callback.
|
|
891
|
+
* The script is calculated in full on each update (same results, slower) when the variable is used outside an
|
|
892
|
+
* eachBar() callback, by two eachBar() blocks, or holds something else than plain data (numbers, strings, booleans,
|
|
893
|
+
* arrays, plain objects, Map, Set). Calling it inside a bar loop throws.
|
|
894
|
+
* @param initial - The value before the first bar.
|
|
895
|
+
* @returns A box whose `.value` reads and writes the variable.
|
|
896
|
+
* @example
|
|
897
|
+
* ```js
|
|
898
|
+
* const dir = persist(0);
|
|
689
899
|
* const trend = eachBar((c) => {
|
|
690
900
|
* if (c.close > c.get(close, 1)) dir.value = 1;
|
|
691
901
|
* else if (c.close < c.get(close, 1)) dir.value = -1;
|
|
@@ -743,13 +953,33 @@ export function persist(initial) {
|
|
|
743
953
|
},
|
|
744
954
|
};
|
|
745
955
|
}
|
|
746
|
-
/**
|
|
956
|
+
/**
|
|
957
|
+
* Declares the script as an indicator: its title, its pane and how its values are shown. Call it once, at the top
|
|
958
|
+
* of the script (a script declares either `indicator()` or `strategy()`). A script without a declaration runs with
|
|
959
|
+
* the title "Untitled" in its own pane.
|
|
960
|
+
* @param title - Name of the script, shown in the legend and the settings.
|
|
961
|
+
* @param options - Pane, short title, number format and drawing limits. Default: `{}` (own pane).
|
|
962
|
+
* @example
|
|
963
|
+
* ```js
|
|
964
|
+
* indicator("My SMA", { overlay: true, precision: 2 });
|
|
965
|
+
* plot(ta.sma(close, 20), "SMA");
|
|
966
|
+
* ```
|
|
967
|
+
*/
|
|
747
968
|
export function indicator(title, options = {}) {
|
|
748
969
|
const c = collector();
|
|
749
970
|
declare(c, 'indicator');
|
|
750
971
|
c.title = title;
|
|
751
972
|
c.shortTitle = options.shorttitle;
|
|
752
|
-
|
|
973
|
+
if (options.pane !== undefined) {
|
|
974
|
+
if (!['price', 'separate', 'auto'].includes(options.pane)) {
|
|
975
|
+
throw new ScriptError(`indicator(): pane is 'price', 'separate' or 'auto', got ${shown(options.pane)}.`);
|
|
976
|
+
}
|
|
977
|
+
if (options.overlay !== undefined)
|
|
978
|
+
throw new ScriptError('indicator(): give overlay or pane, not both.');
|
|
979
|
+
}
|
|
980
|
+
c.overlay = options.pane === 'price' ? true : options.pane === undefined ? (options.overlay ?? false) : false;
|
|
981
|
+
c.paneAuto = options.pane === 'auto';
|
|
982
|
+
c.pane = options.pane;
|
|
753
983
|
c.precision = options.precision;
|
|
754
984
|
c.format = options.format;
|
|
755
985
|
c.scale = options.scale;
|
|
@@ -782,9 +1012,17 @@ class EnumFieldValue {
|
|
|
782
1012
|
/** The fields of each enum, by field: `input.enum()` lists them from its default. */
|
|
783
1013
|
const enumFieldsOf = new WeakMap();
|
|
784
1014
|
/**
|
|
785
|
-
*
|
|
786
|
-
*
|
|
787
|
-
*
|
|
1015
|
+
* Makes an enum: a fixed set of named fields, each with a title, for a choice list (`input.enum()`) or a state with
|
|
1016
|
+
* a few values. Fields compare with `===`; `field.name` is the name, `field.title` and `String(field)` the title.
|
|
1017
|
+
* @param fields - An object of field names and titles, e.g. `{ sma: "Simple", ema: "Exponential" }`; an empty title
|
|
1018
|
+
* is the name.
|
|
1019
|
+
* @returns A frozen object with one {@link EnumField} per name.
|
|
1020
|
+
* @example
|
|
1021
|
+
* ```js
|
|
1022
|
+
* const MaType = defineEnum({ sma: "Simple", ema: "Exponential" });
|
|
1023
|
+
* const maType = input.enum(MaType.sma, "Average");
|
|
1024
|
+
* plot(maType === MaType.ema ? ta.ema(close, 20) : ta.sma(close, 20), "MA");
|
|
1025
|
+
* ```
|
|
788
1026
|
*/
|
|
789
1027
|
export function defineEnum(fields) {
|
|
790
1028
|
if (!isPlainObject(fields) || Object.keys(fields).length === 0) {
|
|
@@ -818,16 +1056,33 @@ function common(opts) {
|
|
|
818
1056
|
out.display = opts.display;
|
|
819
1057
|
if (opts.active !== undefined)
|
|
820
1058
|
out.active = opts.active;
|
|
1059
|
+
if (opts.id !== undefined)
|
|
1060
|
+
out.id = opts.id;
|
|
821
1061
|
return out;
|
|
822
1062
|
}
|
|
823
1063
|
/** Declares the input in the collector and returns its current value (the
|
|
824
1064
|
* host-supplied override when present, else the default). */
|
|
825
1065
|
function registerInput(config, fallbackId) {
|
|
826
1066
|
const c = collector();
|
|
827
|
-
const
|
|
828
|
-
|
|
1067
|
+
const wanted = config.id;
|
|
1068
|
+
let id;
|
|
1069
|
+
if (wanted !== undefined) {
|
|
1070
|
+
if (typeof wanted !== 'string' || !/^[A-Za-z_]\w*$/.test(wanted)) {
|
|
1071
|
+
throw new ScriptError(`input id ${shown(wanted)}: letters, digits and _ only, not starting with a digit, e.g. "fast_length".`);
|
|
1072
|
+
}
|
|
1073
|
+
if (c.inputIds.has(wanted))
|
|
1074
|
+
throw new ScriptError(`Two inputs have the id "${wanted}": give each its own.`);
|
|
1075
|
+
c.inputIds.add(wanted);
|
|
1076
|
+
id = wanted;
|
|
1077
|
+
}
|
|
1078
|
+
else {
|
|
1079
|
+
id = slugId(config.title, fallbackId, c.inputIds);
|
|
1080
|
+
}
|
|
1081
|
+
c.inputConfig.push({ ...config, id });
|
|
829
1082
|
c.defaultInputs[id] = config.defval;
|
|
830
1083
|
const value = c.inputValues[id];
|
|
1084
|
+
if (c.strict && value !== undefined)
|
|
1085
|
+
checkInputValue({ id, ...config }, id, value);
|
|
831
1086
|
return (value === undefined ? config.defval : value);
|
|
832
1087
|
}
|
|
833
1088
|
/** `idKind`: the kind in the id of an input without title (a price input keeps the ids of the float input it was). */
|
|
@@ -835,7 +1090,7 @@ function registerNumeric(type, defval, title, opts = {}, idKind = type) {
|
|
|
835
1090
|
const v = registerInput({ type, defval, title, min: opts.minval, max: opts.maxval, step: opts.step, ...(opts.options ? { options: opts.options } : {}), ...common(opts) }, `input_${idKind}`);
|
|
836
1091
|
return typeof v === 'number' ? v : defval;
|
|
837
1092
|
}
|
|
838
|
-
const COMMON_INPUT_KEYS = ['tooltip', 'inline', 'group', 'confirm', 'display', 'active'];
|
|
1093
|
+
const COMMON_INPUT_KEYS = ['tooltip', 'inline', 'group', 'confirm', 'display', 'active', 'id'];
|
|
839
1094
|
/** The PineScript arguments of each input kind (named arguments are checked against them). */
|
|
840
1095
|
const INPUT_KEYS = {
|
|
841
1096
|
int: ['defval', 'title', 'minval', 'maxval', 'step', 'options', ...COMMON_INPUT_KEYS],
|
|
@@ -890,71 +1145,215 @@ function inputArgs(kind, defvalOrArgs, titleOrArgs, opts) {
|
|
|
890
1145
|
opts: rest,
|
|
891
1146
|
};
|
|
892
1147
|
}
|
|
893
|
-
/**
|
|
894
|
-
*
|
|
895
|
-
*
|
|
1148
|
+
/**
|
|
1149
|
+
* Script inputs: each `input.*` call declares a setting the user can change AND returns its current value (the
|
|
1150
|
+
* user's value when there is one, else the default). The arguments after the default can be named:
|
|
1151
|
+
* `input.int(14, "Length", { minval: 1 })`, `input.int(14, { title: "Length", minval: 1 })` or
|
|
1152
|
+
* `input.int({ defval: 14, title: "Length" })`. The input id is the title in snake case ("Fast length" is
|
|
1153
|
+
* `fast_length`); keep titles stable, a renamed input loses the user's value.
|
|
1154
|
+
*/
|
|
896
1155
|
export const input = strictNamespace('input', {
|
|
1156
|
+
/**
|
|
1157
|
+
* Declares a whole-number setting (a length, a count) and returns its value, rounded to an integer.
|
|
1158
|
+
* @param defval - Default value, or every argument by name (`{ defval, title, minval... }`).
|
|
1159
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_int`).
|
|
1160
|
+
* @param opts - `minval`, `maxval`, `step`, `options` (a choice list) and the common input options.
|
|
1161
|
+
* @returns The current value: the user's value, else `defval`.
|
|
1162
|
+
* @example
|
|
1163
|
+
* ```js
|
|
1164
|
+
* const length = input.int(14, "Length", { minval: 1, maxval: 500 });
|
|
1165
|
+
* plot(ta.rsi(close, length), "RSI");
|
|
1166
|
+
* ```
|
|
1167
|
+
*/
|
|
897
1168
|
int(defval, title, opts) {
|
|
898
1169
|
const a = inputArgs('int', defval, title, opts);
|
|
899
1170
|
return Math.round(registerNumeric('int', a.defval, a.title, a.opts));
|
|
900
1171
|
},
|
|
1172
|
+
/**
|
|
1173
|
+
* Declares a decimal-number setting (a multiplier, a percent, a level) and returns its value.
|
|
1174
|
+
* @param defval - Default value, or every argument by name (`{ defval, title, minval... }`).
|
|
1175
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_float`).
|
|
1176
|
+
* @param opts - `minval`, `maxval`, `step`, `options` (a choice list) and the common input options.
|
|
1177
|
+
* @returns The current value: the user's value, else `defval`.
|
|
1178
|
+
* @example
|
|
1179
|
+
* ```js
|
|
1180
|
+
* const mult = input.float(2.0, "Multiplier", { minval: 0.1, step: 0.1 });
|
|
1181
|
+
* const [basis, upper, lower] = ta.bb(close, 20, mult);
|
|
1182
|
+
* ```
|
|
1183
|
+
*/
|
|
901
1184
|
float(defval, title, opts) {
|
|
902
1185
|
const a = inputArgs('float', defval, title, opts);
|
|
903
1186
|
return registerNumeric('float', a.defval, a.title, a.opts);
|
|
904
1187
|
},
|
|
1188
|
+
/**
|
|
1189
|
+
* Declares an on / off setting (a checkbox) and returns its value. Shown only in the settings by default.
|
|
1190
|
+
* @param defval - Default value, or every argument by name (`{ defval, title... }`).
|
|
1191
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_bool`).
|
|
1192
|
+
* @param opts - The common input options (`group`, `inline`, `tooltip`, `confirm`, `display`, `active`, `id`).
|
|
1193
|
+
* @returns The current value: the user's value, else `defval`.
|
|
1194
|
+
* @example
|
|
1195
|
+
* ```js
|
|
1196
|
+
* const showMa = input.bool(true, "Show MA");
|
|
1197
|
+
* plot(ta.sma(close, 20), "MA", { display: showMa ? display.all : display.none });
|
|
1198
|
+
* ```
|
|
1199
|
+
*/
|
|
905
1200
|
bool(defval, title, opts) {
|
|
906
1201
|
const a = inputArgs('bool', defval, title, opts);
|
|
907
1202
|
return registerInput({ type: 'bool', defval: a.defval, title: a.title, ...common(a.opts) }, 'input_bool');
|
|
908
1203
|
},
|
|
1204
|
+
/**
|
|
1205
|
+
* Declares a text setting and returns its value; with `options`, a drop-down list of choices.
|
|
1206
|
+
* @param defval - Default value (one of `options` when they are given), or every argument by name.
|
|
1207
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_string`).
|
|
1208
|
+
* @param opts - `options` (a choice list) and the common input options.
|
|
1209
|
+
* @returns The current value: the user's value, else `defval`.
|
|
1210
|
+
* @example
|
|
1211
|
+
* ```js
|
|
1212
|
+
* const maType = input.string("EMA", "MA type", { options: ["SMA", "EMA"] });
|
|
1213
|
+
* const ma = maType === "SMA" ? ta.sma(close, 20) : ta.ema(close, 20);
|
|
1214
|
+
* ```
|
|
1215
|
+
*/
|
|
909
1216
|
string(defval, title, opts) {
|
|
910
1217
|
const a = inputArgs('string', defval, title, opts);
|
|
911
1218
|
return registerInput({ type: 'string', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_string');
|
|
912
1219
|
},
|
|
913
|
-
/**
|
|
1220
|
+
/**
|
|
1221
|
+
* Declares a multi-line text setting (lines separated by a newline) and returns its value, e.g. a list of levels
|
|
1222
|
+
* the script parses. Shown only in the settings by default.
|
|
1223
|
+
* @param defval - Default text, or every argument by name.
|
|
1224
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_text_area`).
|
|
1225
|
+
* @param opts - The common input options.
|
|
1226
|
+
* @returns The current text: the user's text, else `defval`.
|
|
1227
|
+
* @example
|
|
1228
|
+
* ```js
|
|
1229
|
+
* const text = input.text_area("100\n105\n110", "Levels");
|
|
1230
|
+
* for (const lvl of text.split("\n")) hline(Number(lvl), "Level " + lvl);
|
|
1231
|
+
* ```
|
|
1232
|
+
*/
|
|
914
1233
|
text_area(defval, title, opts) {
|
|
915
1234
|
const a = inputArgs('text_area', defval, title, opts);
|
|
916
1235
|
return registerInput({ type: 'text_area', defval: a.defval, title: a.title, ...common(a.opts) }, 'input_text_area');
|
|
917
1236
|
},
|
|
918
1237
|
/**
|
|
919
|
-
* Declares a colour
|
|
920
|
-
* `color.new(c, 90)`
|
|
1238
|
+
* Declares a colour setting (a colour picker) and returns its value. The default's transparency is kept to 2
|
|
1239
|
+
* decimals (`color.new(c, 90)` gives the alpha byte 26); a value given by the host is used as it is. Shown only in
|
|
1240
|
+
* the settings by default.
|
|
1241
|
+
* @param defval - Default colour (`color.blue`, `"#2962FF"`, `color.new(...)`), or every argument by name.
|
|
1242
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_color`).
|
|
1243
|
+
* @param opts - The common input options.
|
|
1244
|
+
* @returns The current colour string: the user's colour, else `defval`.
|
|
1245
|
+
* @example
|
|
1246
|
+
* ```js
|
|
1247
|
+
* const lineColor = input.color(color.teal, "Line colour");
|
|
1248
|
+
* plot(ta.ema(close, 20), "EMA", { color: lineColor });
|
|
1249
|
+
* ```
|
|
921
1250
|
*/
|
|
922
1251
|
color(defval, title, opts) {
|
|
923
1252
|
const a = inputArgs('color', defval, title, opts);
|
|
924
1253
|
return registerInput({ type: 'color', defval: inputColorDefault(a.defval), title: a.title, ...common(a.opts) }, 'input_color');
|
|
925
1254
|
},
|
|
926
|
-
/**
|
|
1255
|
+
/**
|
|
1256
|
+
* Declares a source setting (the price a calculation reads) and returns it as a Series. The choices are `open`,
|
|
1257
|
+
* `high`, `low`, `close`, `volume`, `hl2`, `hlc3`, `ohlc4`, `hlcc4`, and the outputs of other scripts on the chart
|
|
1258
|
+
* when the host allows it (an unknown source gives `close`).
|
|
1259
|
+
* @param defval - Default source, by name (`"close"`) or as the built-in Series (`close`), or every argument by
|
|
1260
|
+
* name. Default: `"close"`.
|
|
1261
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_source`).
|
|
1262
|
+
* @param opts - The common input options.
|
|
1263
|
+
* @returns The chosen source as a Series.
|
|
1264
|
+
* @example
|
|
1265
|
+
* ```js
|
|
1266
|
+
* const src = input.source(close, "Source");
|
|
1267
|
+
* plot(ta.sma(src, 20), "SMA");
|
|
1268
|
+
* ```
|
|
1269
|
+
*/
|
|
927
1270
|
source(defval = 'close', title, opts) {
|
|
928
1271
|
const a = inputArgs('source', defval, title, opts);
|
|
929
1272
|
const name = registerInput({ type: 'source', defval: sourceName(a.defval ?? 'close'), title: a.title, ...common(a.opts) }, 'input_source');
|
|
930
1273
|
return sourceSeries(name);
|
|
931
1274
|
},
|
|
932
|
-
/**
|
|
1275
|
+
/**
|
|
1276
|
+
* Declares a timeframe setting (a timeframe picker) and returns its value, for `request.security()` or
|
|
1277
|
+
* `timeframe.change()`.
|
|
1278
|
+
* @param defval - Default timeframe: `"60"` (60 minutes), `"D"`, `"W"`, `"M"`...; `""` is the chart's timeframe.
|
|
1279
|
+
* Or every argument by name.
|
|
1280
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_timeframe`).
|
|
1281
|
+
* @param opts - `options` (a choice list of timeframes) and the common input options.
|
|
1282
|
+
* @returns The current timeframe string (`""`: the chart's timeframe).
|
|
1283
|
+
* @example
|
|
1284
|
+
* ```js
|
|
1285
|
+
* const tf = input.timeframe("D", "Higher timeframe");
|
|
1286
|
+
* const htfClose = request.security("", tf, () => close);
|
|
1287
|
+
* ```
|
|
1288
|
+
*/
|
|
933
1289
|
timeframe(defval, title, opts) {
|
|
934
1290
|
const a = inputArgs('timeframe', defval, title, opts);
|
|
935
1291
|
return registerInput({ type: 'timeframe', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_timeframe');
|
|
936
1292
|
},
|
|
937
|
-
/**
|
|
1293
|
+
/**
|
|
1294
|
+
* Declares a trading-hours setting and returns its value, a session string for `time()` or `inSession()`.
|
|
1295
|
+
* @param defval - Default session: `"HHMM-HHMM"`, optionally followed by `:` and the days (1 = Sunday ...
|
|
1296
|
+
* 7 = Saturday), e.g. `"0930-1600"` or `"0930-1600:23456"`. Or every argument by name.
|
|
1297
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_session`).
|
|
1298
|
+
* @param opts - `options` (a choice list of sessions) and the common input options.
|
|
1299
|
+
* @returns The current session string.
|
|
1300
|
+
* @example
|
|
1301
|
+
* ```js
|
|
1302
|
+
* const sess = input.session("0930-1600", "Session");
|
|
1303
|
+
* bgcolor(color.when(na(time("", sess)).not(), color.new(color.blue, 90)));
|
|
1304
|
+
* ```
|
|
1305
|
+
*/
|
|
938
1306
|
session(defval, title, opts) {
|
|
939
1307
|
const a = inputArgs('session', defval, title, opts);
|
|
940
1308
|
return registerInput({ type: 'session', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_session');
|
|
941
1309
|
},
|
|
942
|
-
/**
|
|
1310
|
+
/**
|
|
1311
|
+
* Declares a symbol setting (a symbol search) and returns its value, a ticker id for `request.security()` of
|
|
1312
|
+
* another symbol.
|
|
1313
|
+
* @param defval - Default ticker id, `"EXCHANGE:TICKER"` (`"NASDAQ:MSFT"`), or every argument by name.
|
|
1314
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_symbol`).
|
|
1315
|
+
* @param opts - `options` (a choice list of symbols) and the common input options.
|
|
1316
|
+
* @returns The current ticker id.
|
|
1317
|
+
* @example
|
|
1318
|
+
* ```js
|
|
1319
|
+
* const other = input.symbol("NASDAQ:MSFT", "Compare with");
|
|
1320
|
+
* plot(request.security(other, "", () => close), "Other close");
|
|
1321
|
+
* ```
|
|
1322
|
+
*/
|
|
943
1323
|
symbol(defval, title, opts) {
|
|
944
1324
|
const a = inputArgs('symbol', defval, title, opts);
|
|
945
1325
|
return registerInput({ type: 'symbol', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_symbol');
|
|
946
1326
|
},
|
|
947
1327
|
/**
|
|
948
|
-
*
|
|
949
|
-
*
|
|
1328
|
+
* Declares a price-level setting (a number field) and returns its value. With `confirm: true` the host can ask the
|
|
1329
|
+
* user to pick it on the chart; an `inline` id shared with an `input.time()` makes one chart point of both.
|
|
1330
|
+
* @param defval - Default price, or every argument by name.
|
|
1331
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_float`).
|
|
1332
|
+
* @param opts - The common input options.
|
|
1333
|
+
* @returns The current price: the user's value, else `defval`.
|
|
1334
|
+
* @example
|
|
1335
|
+
* ```js
|
|
1336
|
+
* const level = input.price(100, "Level", { confirm: true });
|
|
1337
|
+
* hline(level, "Level");
|
|
1338
|
+
* ```
|
|
950
1339
|
*/
|
|
951
1340
|
price(defval, title, opts) {
|
|
952
1341
|
const a = inputArgs('price', defval, title, opts);
|
|
953
1342
|
return registerNumeric('price', a.defval, a.title, a.opts, 'float');
|
|
954
1343
|
},
|
|
955
1344
|
/**
|
|
956
|
-
*
|
|
957
|
-
*
|
|
1345
|
+
* Declares a choice among the fields of an enum made with `defineEnum()` and returns the chosen field. The
|
|
1346
|
+
* settings list the fields by title; the host stores the field's name.
|
|
1347
|
+
* @param defval - Default field (`MaType.sma`), or every argument by name. It must be one of `options`.
|
|
1348
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_enum`).
|
|
1349
|
+
* @param opts - `options` (only these fields of the enum) and the common input options.
|
|
1350
|
+
* @returns The chosen field; compare it with `===`.
|
|
1351
|
+
* @example
|
|
1352
|
+
* ```js
|
|
1353
|
+
* const MaType = defineEnum({ sma: "Simple", ema: "Exponential" });
|
|
1354
|
+
* const maType = input.enum(MaType.sma, "Average");
|
|
1355
|
+
* const ma = maType === MaType.ema ? ta.ema(close, 20) : ta.sma(close, 20);
|
|
1356
|
+
* ```
|
|
958
1357
|
*/
|
|
959
1358
|
enum(defval, title, opts) {
|
|
960
1359
|
const a = inputArgs('enum', defval, title, opts);
|
|
@@ -978,7 +1377,19 @@ export const input = strictNamespace('input', {
|
|
|
978
1377
|
}, 'input_enum');
|
|
979
1378
|
return (choices.find((f) => f.name === name) ?? a.defval);
|
|
980
1379
|
},
|
|
981
|
-
/**
|
|
1380
|
+
/**
|
|
1381
|
+
* Declares a date-and-time setting and returns it as a UNIX time in milliseconds. With `confirm: true` the host
|
|
1382
|
+
* can ask the user to pick it on the chart. Shown only in the settings by default.
|
|
1383
|
+
* @param defval - Default time in ms, usually from `timestamp()`, or every argument by name.
|
|
1384
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_time`).
|
|
1385
|
+
* @param opts - The common input options.
|
|
1386
|
+
* @returns The current time in ms: the user's value, else `defval`.
|
|
1387
|
+
* @example
|
|
1388
|
+
* ```js
|
|
1389
|
+
* const start = input.time(timestamp("2024-01-01"), "Start");
|
|
1390
|
+
* bgcolor(color.when(time.gte(start), color.new(color.green, 90)));
|
|
1391
|
+
* ```
|
|
1392
|
+
*/
|
|
982
1393
|
time(defval, title, opts) {
|
|
983
1394
|
const a = inputArgs('time', defval, title, opts);
|
|
984
1395
|
const v = registerInput({ type: 'time', defval: a.defval, title: a.title, ...common(a.opts) }, 'input_time');
|
|
@@ -986,19 +1397,96 @@ export const input = strictNamespace('input', {
|
|
|
986
1397
|
},
|
|
987
1398
|
});
|
|
988
1399
|
// ── OHLCV builtins ───────────────────────────────────────────────────────────
|
|
1400
|
+
/**
|
|
1401
|
+
* Opening price of each bar, as a Series. In a bar loop, `c.open` is the value of the current bar.
|
|
1402
|
+
* @example
|
|
1403
|
+
* ```js
|
|
1404
|
+
* const body = close.sub(open);
|
|
1405
|
+
* plot(body, "Body", { style: plot.style_columns });
|
|
1406
|
+
* ```
|
|
1407
|
+
*/
|
|
989
1408
|
export const open = Series.fromBars(ctxBars, 'open');
|
|
1409
|
+
/**
|
|
1410
|
+
* Highest price of each bar, as a Series. In a bar loop, `c.high` is the value of the current bar.
|
|
1411
|
+
* @example
|
|
1412
|
+
* ```js
|
|
1413
|
+
* plot(ta.highest(high, 20), "20-bar high");
|
|
1414
|
+
* ```
|
|
1415
|
+
*/
|
|
990
1416
|
export const high = Series.fromBars(ctxBars, 'high');
|
|
1417
|
+
/**
|
|
1418
|
+
* Lowest price of each bar, as a Series. In a bar loop, `c.low` is the value of the current bar.
|
|
1419
|
+
* @example
|
|
1420
|
+
* ```js
|
|
1421
|
+
* plot(ta.lowest(low, 20), "20-bar low");
|
|
1422
|
+
* ```
|
|
1423
|
+
*/
|
|
991
1424
|
export const low = Series.fromBars(ctxBars, 'low');
|
|
1425
|
+
/**
|
|
1426
|
+
* Closing price of each bar, as a Series (on the forming bar, the latest price). The usual source of indicators.
|
|
1427
|
+
* In a bar loop, `c.close` is the value of the current bar.
|
|
1428
|
+
* @example
|
|
1429
|
+
* ```js
|
|
1430
|
+
* plot(ta.sma(close, 20), "SMA");
|
|
1431
|
+
* ```
|
|
1432
|
+
*/
|
|
992
1433
|
export const close = Series.fromBars(ctxBars, 'close');
|
|
1434
|
+
/**
|
|
1435
|
+
* Traded volume of each bar, as a Series (NaN when the data has no volume). In a bar loop, `c.volume`.
|
|
1436
|
+
* @example
|
|
1437
|
+
* ```js
|
|
1438
|
+
* plot(volume, "Volume", { style: plot.style_columns });
|
|
1439
|
+
* ```
|
|
1440
|
+
*/
|
|
993
1441
|
export const volume = Series.fromBars(ctxBars, 'volume');
|
|
1442
|
+
/**
|
|
1443
|
+
* Median price of each bar, (high + low) / 2, as a Series.
|
|
1444
|
+
* @example
|
|
1445
|
+
* ```js
|
|
1446
|
+
* plot(ta.sma(hl2, 10), "Median SMA");
|
|
1447
|
+
* ```
|
|
1448
|
+
*/
|
|
994
1449
|
export const hl2 = new Series(ctxBars, (b) => (b.high + b.low) / 2);
|
|
1450
|
+
/**
|
|
1451
|
+
* Typical price of each bar, (high + low + close) / 3, as a Series.
|
|
1452
|
+
* @example
|
|
1453
|
+
* ```js
|
|
1454
|
+
* plot(ta.sma(hlc3, 20), "Typical SMA");
|
|
1455
|
+
* ```
|
|
1456
|
+
*/
|
|
995
1457
|
export const hlc3 = new Series(ctxBars, (b) => (b.high + b.low + b.close) / 3);
|
|
1458
|
+
/**
|
|
1459
|
+
* Average price of each bar, (open + high + low + close) / 4, as a Series.
|
|
1460
|
+
* @example
|
|
1461
|
+
* ```js
|
|
1462
|
+
* plot(ohlc4, "OHLC average");
|
|
1463
|
+
* ```
|
|
1464
|
+
*/
|
|
996
1465
|
export const ohlc4 = new Series(ctxBars, (b) => (b.open + b.high + b.low + b.close) / 4);
|
|
1466
|
+
/**
|
|
1467
|
+
* Weighted close of each bar, (high + low + close + close) / 4, as a Series.
|
|
1468
|
+
* @example
|
|
1469
|
+
* ```js
|
|
1470
|
+
* plot(ta.ema(hlcc4, 20), "Weighted close EMA");
|
|
1471
|
+
* ```
|
|
1472
|
+
*/
|
|
997
1473
|
export const hlcc4 = new Series(ctxBars, (b) => (b.high + b.low + 2 * b.close) / 4);
|
|
998
|
-
/**
|
|
1474
|
+
/**
|
|
1475
|
+
* Index of each bar, as a Series: 0 on the oldest bar, then 1, 2... In a bar loop, `c.i` is the same number.
|
|
1476
|
+
* @example
|
|
1477
|
+
* ```js
|
|
1478
|
+
* plotshape(bar_index.mod(10).eq(0), "Every 10 bars", { style: shape.circle });
|
|
1479
|
+
* ```
|
|
1480
|
+
*/
|
|
999
1481
|
export const bar_index = new Series(ctxBars, (_b, i) => i);
|
|
1000
1482
|
bar_index.fullHistory = true;
|
|
1001
|
-
/**
|
|
1483
|
+
/**
|
|
1484
|
+
* Index of the last bar of the chart, the same on every bar, as a Series. In a bar loop, `c.n - 1`.
|
|
1485
|
+
* @example
|
|
1486
|
+
* ```js
|
|
1487
|
+
* bgcolor(color.when(bar_index.gte(last_bar_index.sub(9)), color.new(color.blue, 90)), { title: "Last 10 bars" });
|
|
1488
|
+
* ```
|
|
1489
|
+
*/
|
|
1002
1490
|
export const last_bar_index = new Series(ctxBars, (_b, _i, data) => {
|
|
1003
1491
|
// the same value on every bar, changed by a new bar: not kept by an incremental run (#196), but the same in the
|
|
1004
1492
|
// intrabar runs of a backtest (the chart's last bar, #206)
|
|
@@ -1064,6 +1552,11 @@ function editDistance(a, b) {
|
|
|
1064
1552
|
}
|
|
1065
1553
|
/** Names a tool reads to probe an object (promise, JSON, test matchers, module interop): never an error. */
|
|
1066
1554
|
const PROBED_NAMES = new Set(['then', 'toJSON', 'asymmetricMatch', 'nodeType', 'tagName', 'inspect', 'default']);
|
|
1555
|
+
/**
|
|
1556
|
+
* Compile-time check that a namespace's documented interface lists exactly the members of its implementation: a
|
|
1557
|
+
* member added to one but not the other makes the call fail to type-check (the argument becomes `false`).
|
|
1558
|
+
*/
|
|
1559
|
+
function sameKeys(_same) { }
|
|
1067
1560
|
/**
|
|
1068
1561
|
* A namespace whose unknown members throw instead of being `undefined`: `ta.smaa(close, 5)` fails with
|
|
1069
1562
|
* "ta.smaa does not exist. Did you mean ta.sma?" rather than "ta.smaa is not a function", and `color.purpel`
|
|
@@ -1096,7 +1589,7 @@ function strictNamespace(name, members) {
|
|
|
1096
1589
|
* every bar (slow) and returns a Series, not the value of the bar, and it has no per-bar history: the call throws
|
|
1097
1590
|
* with the fix.
|
|
1098
1591
|
*/
|
|
1099
|
-
function outsideBarLoops(members) {
|
|
1592
|
+
function outsideBarLoops(members, ns = 'ta') {
|
|
1100
1593
|
const out = {};
|
|
1101
1594
|
for (const [key, value] of Object.entries(members)) {
|
|
1102
1595
|
if (typeof value !== 'function') {
|
|
@@ -1106,8 +1599,8 @@ function outsideBarLoops(members) {
|
|
|
1106
1599
|
const fn = value;
|
|
1107
1600
|
out[key] = function (...args) {
|
|
1108
1601
|
if (currentBar >= 0) {
|
|
1109
|
-
throw new Error(
|
|
1110
|
-
`Compute it before the loop (const x =
|
|
1602
|
+
throw new Error(`${ns}.${key}() was called inside eachBar(): a ${ns}.* call computes the whole Series at once. ` +
|
|
1603
|
+
`Compute it before the loop (const x = ${ns}.${key}(...)) and read the bar's value with c.get(x). ` +
|
|
1111
1604
|
'For a Pine ta.* call inside an if block or a for loop, use the callsite.* call sites.');
|
|
1112
1605
|
}
|
|
1113
1606
|
return fn.apply(this, args);
|
|
@@ -1199,10 +1692,13 @@ const steppedTa = {
|
|
|
1199
1692
|
correlation: (a, b, length) => stepped('correlation', () => taStep.correlation(length), [a, b], (v, i) => [at(v, 0, i), at(v, 1, i)], 1, () => taSeries.correlation(a, b, length)),
|
|
1200
1693
|
stoch: (source, highSource, lowSource, length) => stepped('stoch', () => taStep.stoch(length), [source, highSource, lowSource], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1, () => taSeries.stoch(source, highSource, lowSource, length)),
|
|
1201
1694
|
};
|
|
1695
|
+
// The library's own `ta` object (bars-first functions) is not a script member.
|
|
1696
|
+
const { ta: _libraryTa, ...taFunctions } = taSeries;
|
|
1697
|
+
void _libraryTa;
|
|
1202
1698
|
/** ta.* with the chart-implicit (bars-first) functions bound to the context,
|
|
1203
|
-
* so scripts call them like
|
|
1204
|
-
|
|
1205
|
-
...
|
|
1699
|
+
* so scripts call them like `ta.tr(true)`, `ta.atr(14)`. Its members and their documentation: {@link TaNamespace}. */
|
|
1700
|
+
const taMembers = strictNamespace('ta', outsideBarLoops({
|
|
1701
|
+
...taFunctions,
|
|
1206
1702
|
...steppedTa,
|
|
1207
1703
|
tr: (handleNa = false) => stepped('tr', () => taStep.tr(handleNa), [high, low, close], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1, () => taSeries.tr(bars(), handleNa)),
|
|
1208
1704
|
atr: (length) => stepped('atr', () => taStep.atr(length), [high, low, close], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1, () => taSeries.atr(bars(), length)),
|
|
@@ -1267,7 +1763,19 @@ export const ta = strictNamespace('ta', outsideBarLoops({
|
|
|
1267
1763
|
iii: barsSeries(taSeries.iii),
|
|
1268
1764
|
wad: barsSeries(taSeries.wad),
|
|
1269
1765
|
wvad: barsSeries(taSeries.wvad),
|
|
1766
|
+
zigzag: (deviation, depth, backstep) => taSeries.zigzag(bars(), deviation, depth, backstep),
|
|
1270
1767
|
}));
|
|
1768
|
+
/**
|
|
1769
|
+
* Technical analysis: moving averages, oscillators, bands, crosses, pivots and volume indicators. Each function
|
|
1770
|
+
* computes a whole Series in one call: call it before any `eachBar()` loop and read a bar's value with `c.get(x)`.
|
|
1771
|
+
* @example
|
|
1772
|
+
* ```js
|
|
1773
|
+
* const fast = ta.ema(close, 12), slow = ta.ema(close, 26);
|
|
1774
|
+
* plot(fast, "Fast"); plot(slow, "Slow");
|
|
1775
|
+
* ```
|
|
1776
|
+
*/
|
|
1777
|
+
export const ta = taMembers;
|
|
1778
|
+
sameKeys(true);
|
|
1271
1779
|
export function fixnan(source) {
|
|
1272
1780
|
if (source instanceof Series)
|
|
1273
1781
|
return Series.fromArray(ctxBars, fixnanValues(source.toArray()));
|
|
@@ -1319,38 +1827,98 @@ function fromGradient(value, bottom_value, top_value, bottom_color, top_color) {
|
|
|
1319
1827
|
const colorAt = (c, i) => (Array.isArray(c) ? c[i] : c);
|
|
1320
1828
|
return Array.from({ length: ctxBars.length }, (_, i) => colorCore.from_gradient(at(v, value, i), at(lo, bottom_value, i), at(hi, top_value, i), colorAt(bottom_color, i), colorAt(top_color, i)));
|
|
1321
1829
|
}
|
|
1322
|
-
|
|
1323
|
-
export const color = strictNamespace('color', {
|
|
1830
|
+
const colorMembers = strictNamespace('color', {
|
|
1324
1831
|
...colorCore,
|
|
1325
1832
|
new: colorCore.new_color,
|
|
1326
1833
|
from_gradient: fromGradient,
|
|
1327
1834
|
when: colorWhen,
|
|
1835
|
+
/**
|
|
1836
|
+
* Not in PineScript: the colour faded by `amount`, from 0 (unchanged) to 1 (invisible): `color.fade(color.red, 0.8)`
|
|
1837
|
+
* is `color.new(color.red, 80)`.
|
|
1838
|
+
*/
|
|
1839
|
+
fade: (c, amount) => {
|
|
1840
|
+
if (typeof amount !== 'number' || !(amount >= 0 && amount <= 1)) {
|
|
1841
|
+
throw new ScriptError(`color.fade(): the amount is from 0 (unchanged) to 1 (invisible), got ${shown(amount)}.`);
|
|
1842
|
+
}
|
|
1843
|
+
return colorCore.new_color(c, amount * 100);
|
|
1844
|
+
},
|
|
1328
1845
|
});
|
|
1329
1846
|
/**
|
|
1330
|
-
*
|
|
1331
|
-
*
|
|
1847
|
+
* Colours: named colours (`color.red`, `color.teal`...), `color.new` for transparency, `color.rgb`, gradients, and
|
|
1848
|
+
* `color.when` to pick a colour per bar for `plot()`, `fill()`, `bgcolor()` and `barcolor()`.
|
|
1849
|
+
* @example
|
|
1850
|
+
* ```js
|
|
1851
|
+
* const up = close.gt(open);
|
|
1852
|
+
* plot(close, "Close", { color: color.when(up, color.green, color.red) });
|
|
1853
|
+
* bgcolor(color.new(color.blue, 90));
|
|
1854
|
+
* ```
|
|
1855
|
+
*/
|
|
1856
|
+
export const color = colorMembers;
|
|
1857
|
+
sameKeys(true);
|
|
1858
|
+
/**
|
|
1859
|
+
* The titles an output gets when the script gives none (`plot` is "Plot", `hline` is "Level"...): the style settings
|
|
1860
|
+
* and the alert lists show them.
|
|
1332
1861
|
*/
|
|
1333
1862
|
export const DEFAULT_OUTPUT_TITLES = {
|
|
1863
|
+
/** Title of a `plot()` without one. */
|
|
1334
1864
|
plot: 'Plot',
|
|
1865
|
+
/** Title of an `hline()` without one. */
|
|
1335
1866
|
hline: 'Level',
|
|
1867
|
+
/** Title of a `fill()` between two plots without one. */
|
|
1336
1868
|
plotFill: 'Plots Background',
|
|
1869
|
+
/** Title of a `fill()` between two hlines without one. */
|
|
1337
1870
|
hlineFill: 'Hlines Background',
|
|
1871
|
+
/** Title of a `plotshape()` without one. */
|
|
1338
1872
|
shape: 'Shapes',
|
|
1873
|
+
/** Title of a `plotchar()` without one. */
|
|
1339
1874
|
char: 'Chars',
|
|
1875
|
+
/** Title of a `plotarrow()` without one. */
|
|
1340
1876
|
arrow: 'Arrows',
|
|
1877
|
+
/** Title of a `bgcolor()` without one. */
|
|
1341
1878
|
bgcolor: 'Background Color',
|
|
1879
|
+
/** Title of a `barcolor()` without one. */
|
|
1342
1880
|
barcolor: 'Bar Color',
|
|
1881
|
+
/** Title of a `plotcandle()` without one. */
|
|
1343
1882
|
candle: 'PlotCandle',
|
|
1883
|
+
/** Title of a `plotbar()` without one. */
|
|
1344
1884
|
bar: 'PlotBar',
|
|
1345
1885
|
};
|
|
1346
|
-
|
|
1347
|
-
|
|
1886
|
+
const PLOT_OPTION_KEYS = ['offset', 'color', 'linewidth', 'style', 'linestyle', 'display', 'histbase', 'force_overlay', 'editable'];
|
|
1887
|
+
/**
|
|
1888
|
+
* Draws a Series on the chart (a line by default, or a histogram, columns, area, circles...) and lists it in the
|
|
1889
|
+
* legend and the settings. Bars whose value is na (NaN or +/-Infinity) are not drawn.
|
|
1890
|
+
* @param source - The values to draw: a Series, or a number for the same value on every bar.
|
|
1891
|
+
* @param title - Name of the plot in the legend, the settings and the alerts. Default: "Plot".
|
|
1892
|
+
* @param options - Colour, width, style, line style, offset, display... Default: `{}` (a blue line).
|
|
1893
|
+
* @returns A handle to pass to `fill()`.
|
|
1894
|
+
* @example
|
|
1895
|
+
* ```js
|
|
1896
|
+
* const fast = plot(ta.ema(close, 12), "Fast", { color: color.teal, linewidth: 2 });
|
|
1897
|
+
* const slow = plot(ta.ema(close, 26), "Slow", { color: color.orange });
|
|
1898
|
+
* fill(fast, slow, color.new(color.gray, 85));
|
|
1899
|
+
* ```
|
|
1900
|
+
*/
|
|
1901
|
+
function plotImpl(source, title = DEFAULT_OUTPUT_TITLES.plot, options = {}) {
|
|
1348
1902
|
if (intrabarRun)
|
|
1349
1903
|
return { id: '', kind: 'plot' }; // dropped: an intrabar run's outputs aren't read
|
|
1350
1904
|
const c = collector();
|
|
1351
|
-
|
|
1905
|
+
if (c.strict && typeof title !== 'string')
|
|
1906
|
+
throw new ScriptError(`plot(): the title is a text, e.g. plot(rsi, "RSI"), got ${shown(title)}.`);
|
|
1907
|
+
checkOptions('plot', options, PLOT_OPTION_KEYS);
|
|
1908
|
+
const series = typeof source === 'number' ? new Series(ctxBars, () => source) : source;
|
|
1909
|
+
if (!(series instanceof Series)) {
|
|
1910
|
+
throw new TypeError(`plot(): the value to plot is a series (close, ta.sma(close, 14)...) or a number, got ${shown(source)}.`);
|
|
1911
|
+
}
|
|
1912
|
+
const id = scriptOptions.plotIds === 'title' ? slugId(title, `plot${c.plotConfig.length}`, (c.plotIdsTaken ??= new Set())) : `plot${c.plotConfig.length}`;
|
|
1352
1913
|
const perBar = Array.isArray(options.color) ? options.color : undefined;
|
|
1353
|
-
const
|
|
1914
|
+
const palette = scriptOptions.palette === true ? DEFAULT_PALETTE : Array.isArray(scriptOptions.palette) && scriptOptions.palette.length ? scriptOptions.palette : null;
|
|
1915
|
+
let fallback = '#2962FF';
|
|
1916
|
+
if (palette && options.color === undefined) {
|
|
1917
|
+
const k = c.paletteUsed ?? 0;
|
|
1918
|
+
c.paletteUsed = k + 1;
|
|
1919
|
+
fallback = palette[k % palette.length];
|
|
1920
|
+
}
|
|
1921
|
+
const staticColor = typeof options.color === 'string' ? options.color : (perBar?.[perBar.length - 1] ?? fallback);
|
|
1354
1922
|
c.plotConfig.push({
|
|
1355
1923
|
id,
|
|
1356
1924
|
title,
|
|
@@ -1407,8 +1975,13 @@ function plotImpl(series, title = DEFAULT_OUTPUT_TITLES.plot, options = {}) {
|
|
|
1407
1975
|
return { id, kind: 'plot' };
|
|
1408
1976
|
}
|
|
1409
1977
|
/**
|
|
1410
|
-
*
|
|
1411
|
-
*
|
|
1978
|
+
* Draws a Series on the chart and lists it in the legend and the settings; `plot.style_*` and `plot.linestyle_*`
|
|
1979
|
+
* pick how it is drawn.
|
|
1980
|
+
* @example
|
|
1981
|
+
* ```js
|
|
1982
|
+
* const fast = plot(ta.ema(close, 12), "Fast", { color: color.teal, linewidth: 2 });
|
|
1983
|
+
* plot(ta.rsi(close, 14), "RSI", { style: plot.style_histogram });
|
|
1984
|
+
* ```
|
|
1412
1985
|
*/
|
|
1413
1986
|
export const plot = Object.assign(plotImpl, {
|
|
1414
1987
|
style_line: 'line',
|
|
@@ -1426,9 +1999,16 @@ export const plot = Object.assign(plotImpl, {
|
|
|
1426
1999
|
linestyle_dotted: 'dotted',
|
|
1427
2000
|
linestyle_dashed: 'dashed',
|
|
1428
2001
|
});
|
|
1429
|
-
/**
|
|
2002
|
+
/**
|
|
2003
|
+
* Draws a horizontal line at a fixed price (a level such as 70 / 30 on an oscillator).
|
|
2004
|
+
* @param price - Price of the line.
|
|
2005
|
+
* @param title - Name of the line in the settings. Default: "Level".
|
|
2006
|
+
* @param options - Colour, line style and width. Default: `{}` (a dashed line).
|
|
2007
|
+
* @returns A handle to pass to `fill()`.
|
|
2008
|
+
*/
|
|
1430
2009
|
function hlineImpl(price, title = DEFAULT_OUTPUT_TITLES.hline, options = {}) {
|
|
1431
2010
|
const c = collector();
|
|
2011
|
+
checkOptions('hline', options, ['color', 'linestyle', 'linewidth', 'editable']);
|
|
1432
2012
|
const id = `hline${c.hlineConfig.length}`;
|
|
1433
2013
|
c.hlineConfig.push({
|
|
1434
2014
|
id,
|
|
@@ -1441,7 +2021,15 @@ function hlineImpl(price, title = DEFAULT_OUTPUT_TITLES.hline, options = {}) {
|
|
|
1441
2021
|
});
|
|
1442
2022
|
return { id, kind: 'hline' };
|
|
1443
2023
|
}
|
|
1444
|
-
/**
|
|
2024
|
+
/**
|
|
2025
|
+
* Draws a horizontal line at a fixed price; `hline.style_*` picks its line style.
|
|
2026
|
+
* @example
|
|
2027
|
+
* ```js
|
|
2028
|
+
* const top = hline(70, "Overbought", { color: color.red });
|
|
2029
|
+
* const bottom = hline(30, "Oversold", { linestyle: hline.style_dotted });
|
|
2030
|
+
* fill(top, bottom, color.new(color.purple, 90));
|
|
2031
|
+
* ```
|
|
2032
|
+
*/
|
|
1445
2033
|
export const hline = Object.assign(hlineImpl, {
|
|
1446
2034
|
style_solid: 'solid',
|
|
1447
2035
|
style_dotted: 'dotted',
|
|
@@ -1637,18 +2225,52 @@ function emitMarkers(kind, condition, title, options) {
|
|
|
1637
2225
|
c.markers.push(location === 'absolute' ? { time, ...template, price: v } : { time, ...template });
|
|
1638
2226
|
}
|
|
1639
2227
|
}
|
|
1640
|
-
|
|
2228
|
+
const SHAPE_OPTION_KEYS = ['style', 'location', 'color', 'text', 'textcolor', 'size', 'offset', 'tooltip', 'force_overlay', 'editable'];
|
|
2229
|
+
/**
|
|
2230
|
+
* Draws a shape (triangle, arrow, circle, label...) on each bar where the condition is true: buy and sell signals.
|
|
2231
|
+
* @param condition - Series that is true (non-zero) on the bars that get a shape. With `location.absolute`, its
|
|
2232
|
+
* value is the price of the shape.
|
|
2233
|
+
* @param title - Name of the shapes in the settings and the alerts. Default: "Shapes".
|
|
2234
|
+
* @param options - Shape (`shape.*`), place (`location.*`), colour, text, size (`size.*`), offset... Default: `{}`
|
|
2235
|
+
* (a cross above the bar).
|
|
2236
|
+
* @example
|
|
2237
|
+
* ```js
|
|
2238
|
+
* const up = ta.crossover(ta.ema(close, 9), ta.ema(close, 21));
|
|
2239
|
+
* plotshape(up, "Buy", { style: shape.triangleup, location: location.belowbar, color: color.green });
|
|
2240
|
+
* ```
|
|
2241
|
+
*/
|
|
1641
2242
|
export function plotshape(condition, title, options = {}) {
|
|
2243
|
+
checkOptions('plotshape', options, SHAPE_OPTION_KEYS, ['color', 'textcolor']);
|
|
1642
2244
|
emitMarkers('shape', condition, title, options);
|
|
1643
2245
|
}
|
|
1644
|
-
/**
|
|
2246
|
+
/**
|
|
2247
|
+
* Draws a character (a letter, an emoji...) on each bar where the condition is true.
|
|
2248
|
+
* @param condition - Series that is true (non-zero) on the bars that get the character. With `location.absolute`,
|
|
2249
|
+
* its value is the price of the character.
|
|
2250
|
+
* @param title - Name of the characters in the settings and the alerts. Default: "Chars".
|
|
2251
|
+
* @param options - Character (`char`), place (`location.*`), colour, text, size (`size.*`), offset... Default: `{}`
|
|
2252
|
+
* (a star above the bar).
|
|
2253
|
+
* @example
|
|
2254
|
+
* ```js
|
|
2255
|
+
* const gapUp = open.gt(high.offset(1));
|
|
2256
|
+
* plotchar(gapUp, "Gap up", { char: "▲", location: location.abovebar, color: color.teal });
|
|
2257
|
+
* ```
|
|
2258
|
+
*/
|
|
1645
2259
|
export function plotchar(condition, title, options = {}) {
|
|
2260
|
+
checkOptions('plotchar', options, [...SHAPE_OPTION_KEYS.filter((k) => k !== 'style'), 'char'], ['color', 'textcolor']);
|
|
1646
2261
|
emitMarkers('char', condition, title, options);
|
|
1647
2262
|
}
|
|
1648
2263
|
/**
|
|
1649
|
-
*
|
|
1650
|
-
*
|
|
1651
|
-
*
|
|
2264
|
+
* Draws an up arrow below the bar where the value is positive and a down arrow above it where it is negative;
|
|
2265
|
+
* nothing for 0 or na. The larger the value, the longer the arrow (between `minheight` and `maxheight`).
|
|
2266
|
+
* @param series - Series whose sign gives the arrow's direction and whose size gives its length.
|
|
2267
|
+
* @param title - Name of the arrows in the settings and the alerts. Default: "Arrows".
|
|
2268
|
+
* @param options - Colours, heights, offset, display. Default: `{}` (green up, red down).
|
|
2269
|
+
* @example
|
|
2270
|
+
* ```js
|
|
2271
|
+
* const change = close.sub(close.offset(1));
|
|
2272
|
+
* plotarrow(change, "Change", { colorup: color.teal, colordown: color.orange });
|
|
2273
|
+
* ```
|
|
1652
2274
|
*/
|
|
1653
2275
|
export function plotarrow(series, title, options = {}) {
|
|
1654
2276
|
if (intrabarRun)
|
|
@@ -1723,14 +2345,36 @@ function emitBarColors(kind, colors, options) {
|
|
|
1723
2345
|
}
|
|
1724
2346
|
}
|
|
1725
2347
|
/**
|
|
1726
|
-
*
|
|
1727
|
-
*
|
|
2348
|
+
* Colours the background of the script's pane behind each bar.
|
|
2349
|
+
* @param colors - One colour for every bar, or one per bar from `color.when()` (no colour on an na entry).
|
|
2350
|
+
* @param options - `offset` (bars to move the colours by), `title` (default "Background Color"), `force_overlay`
|
|
2351
|
+
* (true: colour the price chart's pane), `editable`. Default: `{}`.
|
|
2352
|
+
* @example
|
|
2353
|
+
* ```js
|
|
2354
|
+
* const rsi = ta.rsi(close, 14);
|
|
2355
|
+
* bgcolor(color.when(rsi.gt(70), color.new(color.red, 85)));
|
|
2356
|
+
* ```
|
|
1728
2357
|
*/
|
|
1729
2358
|
export function bgcolor(colors, options = {}) {
|
|
2359
|
+
if (ctx?.strict)
|
|
2360
|
+
checkColor('bgcolor(): the colour', colors);
|
|
2361
|
+
checkOptions('bgcolor', options, ['offset', 'title', 'force_overlay', 'editable']);
|
|
1730
2362
|
emitBarColors('bgcolor', colors, options);
|
|
1731
2363
|
}
|
|
1732
|
-
/**
|
|
2364
|
+
/**
|
|
2365
|
+
* Colours the chart's candles or bars, replacing their usual colours.
|
|
2366
|
+
* @param colors - One colour for every bar, or one per bar from `color.when()` (usual colour on an na entry).
|
|
2367
|
+
* @param options - `title` (default "Bar Color") and `editable`. Default: `{}`.
|
|
2368
|
+
* @example
|
|
2369
|
+
* ```js
|
|
2370
|
+
* const trendUp = close.gt(ta.sma(close, 50));
|
|
2371
|
+
* barcolor(color.when(trendUp, color.green, color.red));
|
|
2372
|
+
* ```
|
|
2373
|
+
*/
|
|
1733
2374
|
export function barcolor(colors, options = {}) {
|
|
2375
|
+
if (ctx?.strict)
|
|
2376
|
+
checkColor('barcolor(): the colour', colors);
|
|
2377
|
+
checkOptions('barcolor', options, ['title', 'editable']);
|
|
1734
2378
|
emitBarColors('barcolor', colors, options);
|
|
1735
2379
|
}
|
|
1736
2380
|
/** Colour of bar i: undefined when the argument is not given, 'transparent' for an na entry. */
|
|
@@ -1758,7 +2402,14 @@ const staticColor = (col) => (typeof col === 'string' ? col : undefined);
|
|
|
1758
2402
|
* Colours of a plotcandle / plotbar argument left out, as the PineScript compiler declares them and the chart draws
|
|
1759
2403
|
* them (reference: body / bar #2962FF, wick #737375, border #000000; the wick and border do not follow the body).
|
|
1760
2404
|
*/
|
|
1761
|
-
export const DEFAULT_CANDLE_COLORS = {
|
|
2405
|
+
export const DEFAULT_CANDLE_COLORS = {
|
|
2406
|
+
/** Body colour (and the colour of `plotbar()` bars). */
|
|
2407
|
+
color: '#2962FF',
|
|
2408
|
+
/** Wick colour. */
|
|
2409
|
+
wickColor: '#737375',
|
|
2410
|
+
/** Border colour. */
|
|
2411
|
+
borderColor: '#000000',
|
|
2412
|
+
};
|
|
1762
2413
|
/** The palettes of the per-bar colour arguments of a plotcandle / plotbar that have one. */
|
|
1763
2414
|
function candlePalettes(cols) {
|
|
1764
2415
|
const palettes = {};
|
|
@@ -1772,8 +2423,19 @@ function candlePalettes(cols) {
|
|
|
1772
2423
|
/** A colour argument, or the default when it is left out. */
|
|
1773
2424
|
const orDefault = (col, fallback) => (col === undefined ? fallback : col);
|
|
1774
2425
|
/**
|
|
1775
|
-
*
|
|
1776
|
-
*
|
|
2426
|
+
* Draws candles from four Series (for example the candles of another symbol, or smoothed prices). A bar where one of
|
|
2427
|
+
* the four values is na has no candle.
|
|
2428
|
+
* @param open - Open of each candle.
|
|
2429
|
+
* @param high - High of each candle.
|
|
2430
|
+
* @param low - Low of each candle.
|
|
2431
|
+
* @param close - Close of each candle.
|
|
2432
|
+
* @param title - Name of the candles in the settings. Default: "PlotCandle".
|
|
2433
|
+
* @param options - Body, wick and border colours, display, force_overlay, editable. Default: `{}`.
|
|
2434
|
+
* @example
|
|
2435
|
+
* ```js
|
|
2436
|
+
* const o = ta.ema(open, 5), h = ta.ema(high, 5), l = ta.ema(low, 5), c = ta.ema(close, 5);
|
|
2437
|
+
* plotcandle(o, h, l, c, "Smoothed", { color: color.when(c.gt(o), color.teal, color.red) });
|
|
2438
|
+
* ```
|
|
1777
2439
|
*/
|
|
1778
2440
|
export function plotcandle(open, high, low, close, title, options = {}) {
|
|
1779
2441
|
if (intrabarRun)
|
|
@@ -1815,8 +2477,17 @@ export function plotcandle(open, high, low, close, title, options = {}) {
|
|
|
1815
2477
|
});
|
|
1816
2478
|
}
|
|
1817
2479
|
/**
|
|
1818
|
-
*
|
|
1819
|
-
*
|
|
2480
|
+
* Draws open-high-low-close bars from four Series. A bar where one of the four values is na is not drawn.
|
|
2481
|
+
* @param open - Open of each bar.
|
|
2482
|
+
* @param high - High of each bar.
|
|
2483
|
+
* @param low - Low of each bar.
|
|
2484
|
+
* @param close - Close of each bar.
|
|
2485
|
+
* @param title - Name of the bars in the settings. Default: "PlotBar".
|
|
2486
|
+
* @param options - Colour, display, force_overlay, editable. Default: `{}`.
|
|
2487
|
+
* @example
|
|
2488
|
+
* ```js
|
|
2489
|
+
* plotbar(open, high, low, close, "Bars", { color: color.when(close.gt(open), color.green, color.red) });
|
|
2490
|
+
* ```
|
|
1820
2491
|
*/
|
|
1821
2492
|
export function plotbar(open, high, low, close, title, options = {}) {
|
|
1822
2493
|
if (intrabarRun)
|
|
@@ -1883,6 +2554,20 @@ function outerWritesOf(fn) {
|
|
|
1883
2554
|
}
|
|
1884
2555
|
return found;
|
|
1885
2556
|
}
|
|
2557
|
+
/**
|
|
2558
|
+
* Runs a function on every bar, oldest first, for logic that needs the bar's values one at a time (state, ifs,
|
|
2559
|
+
* loops). The function reads the bar through `c` (`c.close`, `c.get(series)`, `c.get(series, 1)` for one bar back)
|
|
2560
|
+
* and returns the bar's value of the Series that `eachBar` gives back (na when it returns nothing).
|
|
2561
|
+
* @param fn - Called once per bar with the bar's context; returns a number (or true / false) for that bar.
|
|
2562
|
+
* @returns Series of the values the function returned.
|
|
2563
|
+
* @example
|
|
2564
|
+
* ```js
|
|
2565
|
+
* const fast = ta.sma(close, 10);
|
|
2566
|
+
* let count = 0;
|
|
2567
|
+
* const streak = eachBar((c) => (count = c.get(close) > c.get(fast) ? count + 1 : 0));
|
|
2568
|
+
* plot(streak, "Bars above");
|
|
2569
|
+
* ```
|
|
2570
|
+
*/
|
|
1886
2571
|
export function eachBar(fn) {
|
|
1887
2572
|
return runBlock(fn);
|
|
1888
2573
|
}
|
|
@@ -2332,6 +3017,8 @@ for (const name of [...STRATEGY_NUMBER_VARIABLES, ...STRATEGY_TEXT_VARIABLES]) {
|
|
|
2332
3017
|
* ```
|
|
2333
3018
|
*/
|
|
2334
3019
|
export const strategy = Object.defineProperties(Object.assign((title, options) => declareStrategy(title, options), strategyMembers), variableGetters);
|
|
3020
|
+
sameKeys(true);
|
|
3021
|
+
sameKeys(true);
|
|
2335
3022
|
/** The symbol fields a {@link SymbolInfo} gives to `syminfo.*` inside `request.security`. */
|
|
2336
3023
|
const SYMBOL_INFO_KEYS = [
|
|
2337
3024
|
'timezone', 'session', 'regularSession', 'mintick', 'minmove', 'pricescale', 'pointvalue', 'mincontract', 'symbolType',
|
|
@@ -2383,7 +3070,8 @@ export const timeframe = {
|
|
|
2383
3070
|
return chartTimeframe().period;
|
|
2384
3071
|
},
|
|
2385
3072
|
get main_period() {
|
|
2386
|
-
|
|
3073
|
+
const main = chartCtx.mainTimeframe;
|
|
3074
|
+
return main ? timeframeCore.info(main).period : chartTimeframe().period;
|
|
2387
3075
|
},
|
|
2388
3076
|
get multiplier() {
|
|
2389
3077
|
return chartTimeframe().multiplier;
|
|
@@ -2643,22 +3331,74 @@ function calendar(fn) {
|
|
|
2643
3331
|
return time instanceof Series ? Series.fromArray(ctxBars, time.toArray().map((t) => fn(t, tz))) : fn(time, tz);
|
|
2644
3332
|
});
|
|
2645
3333
|
}
|
|
2646
|
-
/**
|
|
3334
|
+
/**
|
|
3335
|
+
* The year of a time (2025...). Works on one time or on a Series of times (`year(time)` gives the value of each bar).
|
|
3336
|
+
* @example
|
|
3337
|
+
* ```js
|
|
3338
|
+
* const newYear = year(time).neq(year(time).offset(1));
|
|
3339
|
+
* bgcolor(color.when(newYear, color.new(color.blue, 80)));
|
|
3340
|
+
* ```
|
|
3341
|
+
*/
|
|
2647
3342
|
export const year = calendar(timeCore.year);
|
|
2648
|
-
/**
|
|
3343
|
+
/**
|
|
3344
|
+
* The month of a time, 1 (January) to 12. Works on one time or on a Series of times (`month(time)` gives the value of each bar).
|
|
3345
|
+
* @example
|
|
3346
|
+
* ```js
|
|
3347
|
+
* const january = month(time).eq(1);
|
|
3348
|
+
* bgcolor(color.when(january, color.new(color.teal, 85)));
|
|
3349
|
+
* ```
|
|
3350
|
+
*/
|
|
2649
3351
|
export const month = calendar(timeCore.month);
|
|
2650
|
-
/**
|
|
3352
|
+
/**
|
|
3353
|
+
* The week of the year of a time, 1 to 53. Works on one time or on a Series of times (`weekofyear(time)` gives the value of each bar).
|
|
3354
|
+
* @example
|
|
3355
|
+
* ```js
|
|
3356
|
+
* plot(weekofyear(time), "Week");
|
|
3357
|
+
* ```
|
|
3358
|
+
*/
|
|
2651
3359
|
export const weekofyear = calendar(timeCore.weekofyear);
|
|
2652
|
-
/**
|
|
3360
|
+
/**
|
|
3361
|
+
* The day of the month of a time, 1 to 31. Works on one time or on a Series of times (`dayofmonth(time)` gives the value of each bar).
|
|
3362
|
+
* @example
|
|
3363
|
+
* ```js
|
|
3364
|
+
* plot(dayofmonth(time, "UTC"), "Day of month");
|
|
3365
|
+
* ```
|
|
3366
|
+
*/
|
|
2653
3367
|
export const dayofmonth = calendar(timeCore.dayofmonth);
|
|
2654
|
-
/**
|
|
2655
|
-
|
|
3368
|
+
/**
|
|
3369
|
+
* The day of the week of a time, 1 (Sunday) to 7 (Saturday), on one time or a Series of times; compare it with the
|
|
3370
|
+
* `dayofweek.monday`... constants.
|
|
3371
|
+
* @example
|
|
3372
|
+
* ```js
|
|
3373
|
+
* const monday = dayofweek(time).eq(dayofweek.monday);
|
|
3374
|
+
* bgcolor(color.when(monday, color.new(color.gray, 90)));
|
|
3375
|
+
* ```
|
|
3376
|
+
*/
|
|
2656
3377
|
export const dayofweek = Object.assign(calendar(timeCore.dayofweek), pineConstants.daysOfWeek);
|
|
2657
|
-
/**
|
|
3378
|
+
/**
|
|
3379
|
+
* The hour of a time, 0 to 23. Works on one time or on a Series of times (`hour(time)` gives the value of each bar).
|
|
3380
|
+
* @example
|
|
3381
|
+
* ```js
|
|
3382
|
+
* const morning = hour(time).lt(12);
|
|
3383
|
+
* bgcolor(color.when(morning, color.new(color.orange, 90)));
|
|
3384
|
+
* ```
|
|
3385
|
+
*/
|
|
2658
3386
|
export const hour = calendar(timeCore.hour);
|
|
2659
|
-
/**
|
|
3387
|
+
/**
|
|
3388
|
+
* The minute of a time, 0 to 59. Works on one time or on a Series of times (`minute(time)` gives the value of each bar).
|
|
3389
|
+
* @example
|
|
3390
|
+
* ```js
|
|
3391
|
+
* plot(minute(time), "Minute");
|
|
3392
|
+
* ```
|
|
3393
|
+
*/
|
|
2660
3394
|
export const minute = calendar(timeCore.minute);
|
|
2661
|
-
/**
|
|
3395
|
+
/**
|
|
3396
|
+
* The second of a time, 0 to 59. Works on one time or on a Series of times (`second(time)` gives the value of each bar).
|
|
3397
|
+
* @example
|
|
3398
|
+
* ```js
|
|
3399
|
+
* plot(second(time), "Second");
|
|
3400
|
+
* ```
|
|
3401
|
+
*/
|
|
2662
3402
|
export const second = calendar(timeCore.second);
|
|
2663
3403
|
export function timestamp(first, ...rest) {
|
|
2664
3404
|
if (typeof first === 'number') {
|
|
@@ -2670,23 +3410,41 @@ export function timestamp(first, ...rest) {
|
|
|
2670
3410
|
const [y, m, d, h, mi, s] = rest;
|
|
2671
3411
|
return timeCore.timestamp(first, y, m, d, h, mi, s);
|
|
2672
3412
|
}
|
|
2673
|
-
/**
|
|
3413
|
+
/**
|
|
3414
|
+
* Whether a time is inside a session (trading hours).
|
|
3415
|
+
* @param time - A time in UNIX milliseconds, e.g. `c.time` in `eachBar()`.
|
|
3416
|
+
* @param session - Session hours and days: "0930-1600", "0930-1600:23456" (Monday to Friday), "1800-0500" (overnight).
|
|
3417
|
+
* @param timezone - Time zone of the session hours. Default: the exchange's.
|
|
3418
|
+
* @returns true when the time is in the session.
|
|
3419
|
+
* @example
|
|
3420
|
+
* ```js
|
|
3421
|
+
* const regular = eachBar((c) => inSession(c.time, "0930-1600"));
|
|
3422
|
+
* bgcolor(color.when(regular, color.new(color.blue, 92)));
|
|
3423
|
+
* ```
|
|
3424
|
+
*/
|
|
2674
3425
|
export function inSession(time, session, timezone) {
|
|
2675
3426
|
return timeCore.inSession(time, session, timezone ?? exchangeTimezone());
|
|
2676
3427
|
}
|
|
2677
|
-
/**
|
|
3428
|
+
/**
|
|
3429
|
+
* Text functions: `str.tostring` (a number as text), `str.format` (a pattern with values), `str.format_time` (a date),
|
|
3430
|
+
* search, replace, split, case... `str.format_time` and the dates of `str.format` use the exchange's time zone by
|
|
3431
|
+
* default.
|
|
3432
|
+
* @example
|
|
3433
|
+
* ```js
|
|
3434
|
+
* eachBar((c) => {
|
|
3435
|
+
* if (barstate.islast) log.info(str.format("Close {0} at {1}", c.get(close), str.format_time(c.get(time), "HH:mm")));
|
|
3436
|
+
* });
|
|
3437
|
+
* ```
|
|
3438
|
+
*/
|
|
2678
3439
|
export const str = strictNamespace('str', {
|
|
2679
3440
|
...strCore,
|
|
2680
3441
|
// format.mintick uses the chart symbol's tick and price scale (syminfo.mintick, syminfo.pricescale)
|
|
2681
3442
|
tostring: ((value, format, mintick, pricescale) => format === 'mintick' && mintick === undefined
|
|
2682
3443
|
? strCore.tostring(value, format, syminfo.mintick, pricescale ?? syminfo.pricescale)
|
|
2683
3444
|
: strCore.tostring(value, format, mintick, pricescale)),
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
format(pattern, ...args) {
|
|
2688
|
-
return formatMessage(pattern, args, exchangeTimezone);
|
|
2689
|
-
},
|
|
3445
|
+
// the exchange time zone by default; the documentation is the library function's
|
|
3446
|
+
format_time: ((time, format = "yyyy-MM-dd'T'HH:mm:ssZ", timezone) => strCore.format_time(time, format, timezone ?? exchangeTimezone())),
|
|
3447
|
+
format: ((pattern, ...args) => formatMessage(pattern, args, exchangeTimezone)),
|
|
2690
3448
|
});
|
|
2691
3449
|
// ── Session values (issue #100) ──────────────────────────────────────────────
|
|
2692
3450
|
/** Bar time in ms (PineScript `time`). */
|
|
@@ -2728,20 +3486,30 @@ function chartSessionPeriods(timeframeString, session, timezone) {
|
|
|
2728
3486
|
const { bars } = sessionBars();
|
|
2729
3487
|
return sessionPeriods(bars, { ...chartCtx, timezone: exchangeTimezone() }, timeframeString, session, timezone);
|
|
2730
3488
|
}
|
|
3489
|
+
/**
|
|
3490
|
+
* The open time of the period of `tf` that holds each bar, in UNIX milliseconds; na on bars outside `session`.
|
|
3491
|
+
* @param tf - Timeframe of the periods: "D", "W", "60"... Default: the chart's.
|
|
3492
|
+
* @param session - Session hours, e.g. "0930-1600"; bars outside it give na. Default: the symbol's.
|
|
3493
|
+
* @param timezone - Time zone of the session hours. Default: the exchange's.
|
|
3494
|
+
* @returns Series of period open times.
|
|
3495
|
+
*/
|
|
2731
3496
|
function timeFunction(tf, session, timezone) {
|
|
2732
3497
|
collector();
|
|
2733
3498
|
const { open } = chartSessionPeriods(tf || chartTimeframe().period, session, timezone);
|
|
2734
3499
|
return perBar((t) => open(t));
|
|
2735
3500
|
}
|
|
3501
|
+
/**
|
|
3502
|
+
* The close time of the period of `tf` that holds each bar, in UNIX milliseconds; na on bars outside `session`.
|
|
3503
|
+
* @param tf - Timeframe of the periods: "D", "W", "60"... Default: the chart's.
|
|
3504
|
+
* @param session - Session hours, e.g. "0930-1600"; bars outside it give na. Default: the symbol's.
|
|
3505
|
+
* @param timezone - Time zone of the session hours. Default: the exchange's.
|
|
3506
|
+
* @returns Series of period close times.
|
|
3507
|
+
*/
|
|
2736
3508
|
function timeCloseFunction(tf, session, timezone) {
|
|
2737
3509
|
collector();
|
|
2738
3510
|
const { close } = chartSessionPeriods(tf || chartTimeframe().period, session, timezone);
|
|
2739
3511
|
return perBar((t) => close(t));
|
|
2740
3512
|
}
|
|
2741
|
-
/**
|
|
2742
|
-
* PineScript `time`: the bar open time in ms (a Series), and `time(timeframe?, session?, timezone?)`:
|
|
2743
|
-
* the open time of the `timeframe` period that contains the bar, `na` outside `session`.
|
|
2744
|
-
*/
|
|
2745
3513
|
/** Current time of the run in ms, see `ChartContext.now`. */
|
|
2746
3514
|
let runNow = NaN;
|
|
2747
3515
|
/** PineScript `timenow`: the current time in ms, the same on every bar of a run (`ChartContext.now`). */
|
|
@@ -2749,10 +3517,23 @@ export const timenow = new Series(ctxBars, () => {
|
|
|
2749
3517
|
incremental.nonIncremental('timenow');
|
|
2750
3518
|
return runNow;
|
|
2751
3519
|
});
|
|
3520
|
+
/**
|
|
3521
|
+
* The open time of each bar, in UNIX milliseconds (a Series). Called as `time(tf?, session?, timezone?)`: the open
|
|
3522
|
+
* time of the `tf` period that holds the bar, na outside `session`.
|
|
3523
|
+
* @example
|
|
3524
|
+
* ```js
|
|
3525
|
+
* const newDay = time("D").neq(time("D").offset(1));
|
|
3526
|
+
* bgcolor(color.when(newDay, color.new(color.gray, 85)));
|
|
3527
|
+
* ```
|
|
3528
|
+
*/
|
|
2752
3529
|
export const time = callableSeries(new Series(ctxBars, (b) => barTime(b)), timeFunction);
|
|
2753
3530
|
/**
|
|
2754
|
-
*
|
|
2755
|
-
*
|
|
3531
|
+
* The close time of each bar, in UNIX milliseconds (a Series). Called as `time_close(tf?, session?, timezone?)`: the
|
|
3532
|
+
* close time of the `tf` period that holds the bar, na outside `session`.
|
|
3533
|
+
* @example
|
|
3534
|
+
* ```js
|
|
3535
|
+
* plot(time_close.sub(time).div(60000), "Bar minutes");
|
|
3536
|
+
* ```
|
|
2756
3537
|
*/
|
|
2757
3538
|
export const time_close = callableSeries(new Series(ctxBars, (_b, i) => sessionBars().bars.closeOf(barTime(ctxBars.bars[i]), chartTimeframe().period)), timeCloseFunction);
|
|
2758
3539
|
/** PineScript `time_tradingday`: 00:00 UTC of the trading day of each bar, in ms. */
|
|
@@ -2954,7 +3735,7 @@ function security(symbol, timeframe, expression, gaps = barmerge.gaps_off, looka
|
|
|
2954
3735
|
let result;
|
|
2955
3736
|
let values;
|
|
2956
3737
|
ctxBars.setAll(htf);
|
|
2957
|
-
chartCtx = { ...chartCtx, timeframe: tf };
|
|
3738
|
+
chartCtx = { ...chartCtx, timeframe: tf, mainTimeframe: chartCtx.mainTimeframe ?? chartCtx.timeframe };
|
|
2958
3739
|
try {
|
|
2959
3740
|
result = expression();
|
|
2960
3741
|
const parts = Array.isArray(result) ? result : [result];
|
|
@@ -2991,7 +3772,13 @@ function runExternal(symbol, heikin, tf, expression, ignoreInvalid, own) {
|
|
|
2991
3772
|
ctxBars.setAll(bars);
|
|
2992
3773
|
// the expression sees that symbol: its ticker, timeframe, calendar and properties (the chart's own symbol stays the
|
|
2993
3774
|
// main one)
|
|
2994
|
-
const seen = {
|
|
3775
|
+
const seen = {
|
|
3776
|
+
...chartCtx,
|
|
3777
|
+
tickerid: symbol,
|
|
3778
|
+
timeframe: tf,
|
|
3779
|
+
mainTickerid: chartCtx.mainTickerid ?? chartCtx.tickerid,
|
|
3780
|
+
mainTimeframe: chartCtx.mainTimeframe ?? chartCtx.timeframe,
|
|
3781
|
+
};
|
|
2995
3782
|
for (const key of SYMBOL_INFO_KEYS)
|
|
2996
3783
|
seen[key] = info[key];
|
|
2997
3784
|
chartCtx = seen;
|
|
@@ -3239,7 +4026,7 @@ function earningsCall(...args) {
|
|
|
3239
4026
|
const list = (symbolEvents(ticker).earnings ?? []).filter((e) => e.time <= runNow);
|
|
3240
4027
|
return eventSeries(list.map((e) => e.time), eventField(list, field, 'request.earnings', ticker), a[2], a[3]);
|
|
3241
4028
|
}
|
|
3242
|
-
|
|
4029
|
+
const requestMembers = strictNamespace('request', {
|
|
3243
4030
|
security: securityCall,
|
|
3244
4031
|
security_lower_tf: securityLowerTfCall,
|
|
3245
4032
|
seed: seedCall,
|
|
@@ -3247,39 +4034,67 @@ export const request = strictNamespace('request', {
|
|
|
3247
4034
|
splits: splitsCall,
|
|
3248
4035
|
earnings: earningsCall,
|
|
3249
4036
|
});
|
|
4037
|
+
/**
|
|
4038
|
+
* Data from other symbols, timeframes and sources: `request.security` (another symbol or timeframe),
|
|
4039
|
+
* `request.security_lower_tf` (the lower-timeframe bars inside each bar), `request.seed` (a separately published data series),
|
|
4040
|
+
* dividends, splits and earnings. Call it before any `eachBar()` loop.
|
|
4041
|
+
* @example
|
|
4042
|
+
* ```js
|
|
4043
|
+
* const dailyClose = request.security("", "D", () => close);
|
|
4044
|
+
* plot(dailyClose, "Daily close");
|
|
4045
|
+
* ```
|
|
4046
|
+
*/
|
|
4047
|
+
export const request = requestMembers;
|
|
4048
|
+
sameKeys(true);
|
|
3250
4049
|
const loopBar = () => currentBar;
|
|
3251
|
-
/** Wraps a drawing namespace and keeps its `all` getter (the live drawings in creation order). */
|
|
3252
4050
|
function drawings(name, members, all) {
|
|
3253
4051
|
const out = drawingNamespace(name, members, loopBar);
|
|
3254
4052
|
return Object.defineProperty(out, 'all', { get: all, enumerable: true });
|
|
3255
4053
|
}
|
|
4054
|
+
// The members are typed by their modules, so that the editor shows each function's documentation.
|
|
3256
4055
|
const lineNs = drawings('line', { ...lineCore, ...pineConstants.lineStyles }, () => lineCore.all());
|
|
3257
|
-
/**
|
|
4056
|
+
/**
|
|
4057
|
+
* Lines between two chart points: `line.new()` draws one, `line.set_*` / `line.get_*` move and read it, `line.style_*`
|
|
4058
|
+
* are its styles, `line.all` lists the live lines.
|
|
4059
|
+
*/
|
|
3258
4060
|
export const line = lineNs;
|
|
3259
4061
|
const labelNs = drawings('label', { ...labelCore, ...pineConstants.labelStyles }, () => labelCore.all());
|
|
3260
|
-
/**
|
|
4062
|
+
/**
|
|
4063
|
+
* Text boxes and shapes at a chart point: `label.new()` draws one, `label.set_*` / `label.get_*` change and read it,
|
|
4064
|
+
* `label.style_*` are its styles, `label.all` lists the live labels.
|
|
4065
|
+
*/
|
|
3261
4066
|
export const label = labelNs;
|
|
3262
4067
|
const boxNs = drawings('box', { ...boxCore }, () => boxCore.all());
|
|
3263
|
-
/**
|
|
4068
|
+
/**
|
|
4069
|
+
* Rectangles between two x coordinates and two prices, with optional text: `box.new()` draws one, `box.set_*` /
|
|
4070
|
+
* `box.get_*` change and read it, `box.all` lists the live boxes.
|
|
4071
|
+
*/
|
|
3264
4072
|
export const box = boxNs;
|
|
3265
4073
|
const linefillNs = drawings('linefill', { ...linefillCore }, () => linefillCore.all());
|
|
3266
|
-
/**
|
|
4074
|
+
/**
|
|
4075
|
+
* Colour fills between two lines that follow the lines when they move: `linefill.new()`, `linefill.set_color()`,
|
|
4076
|
+
* `linefill.all`.
|
|
4077
|
+
*/
|
|
3267
4078
|
export const linefill = linefillNs;
|
|
3268
4079
|
const polylineNs = drawings('polyline', { ...polylineCore }, () => polylineCore.all());
|
|
3269
|
-
/**
|
|
4080
|
+
/**
|
|
4081
|
+
* Shapes through many chart points, straight or curved, open or closed and filled: `polyline.new()`,
|
|
4082
|
+
* `polyline.delete()`, `polyline.all`.
|
|
4083
|
+
*/
|
|
3270
4084
|
export const polyline = polylineNs;
|
|
3271
4085
|
const tableNs = drawings('table', { ...tableCore }, () => tableCore.all());
|
|
3272
4086
|
/**
|
|
3273
|
-
*
|
|
4087
|
+
* Tables fixed at a place of the pane, for values and dashboards: `table.new()` creates one, `table.cell()` fills it,
|
|
4088
|
+
* `table.all` lists the live tables. The live tables go to `result.tables`.
|
|
3274
4089
|
*/
|
|
3275
4090
|
export const table = tableNs;
|
|
4091
|
+
sameKeys(true);
|
|
3276
4092
|
/** PineScript `position.*` constants (table positions). */
|
|
3277
4093
|
export { position };
|
|
3278
|
-
/**
|
|
4094
|
+
/** Text constants: `text.format_*` (bold, italic), `text.align_*` (alignment) and `text.wrap_*` (wrapping). */
|
|
3279
4095
|
export const text = { ...textCore };
|
|
3280
|
-
|
|
3281
|
-
|
|
3282
|
-
export const { shape, location, size, xloc, yloc, extend, display, format, font, scale, order, currency, adjustment } = pineConstants;
|
|
4096
|
+
// The constant namespaces (`shape.triangleup`, `size.small`, `xloc.bar_time`...), each documented in constants.ts.
|
|
4097
|
+
export { shape, location, size, xloc, yloc, extend, display, format, font, scale, order, currency, adjustment } from './constants.js';
|
|
3283
4098
|
/**
|
|
3284
4099
|
* PineScript `chart.point.*`. `chart.point.now(price?)` is the point of the current bar
|
|
3285
4100
|
* (index, time, and `price`, default the close), so it runs inside eachBar().
|
|
@@ -3337,13 +4152,32 @@ export const chart = {
|
|
|
3337
4152
|
},
|
|
3338
4153
|
},
|
|
3339
4154
|
};
|
|
3340
|
-
/**
|
|
3341
|
-
*
|
|
4155
|
+
/**
|
|
4156
|
+
* Makes a Series from an array of numbers, one per bar (oldest first), e.g. values collected inside `eachBar()`.
|
|
4157
|
+
* @param values - One value per bar; NaN is na.
|
|
4158
|
+
* @returns Series of the values.
|
|
4159
|
+
* @example
|
|
4160
|
+
* ```js
|
|
4161
|
+
* const ranges = [];
|
|
4162
|
+
* eachBar((c) => { ranges.push(c.high - c.low); });
|
|
4163
|
+
* plot(seriesOf(ranges), "Range");
|
|
4164
|
+
* ```
|
|
4165
|
+
*/
|
|
3342
4166
|
export function seriesOf(values) {
|
|
3343
4167
|
collector();
|
|
3344
4168
|
return Series.fromArray(ctxBars, values);
|
|
3345
4169
|
}
|
|
3346
|
-
/**
|
|
4170
|
+
/**
|
|
4171
|
+
* Declares a condition users can create an alert on (in the app's alert dialog). It does not send an alert itself.
|
|
4172
|
+
* @param condition - Series that is true (non-zero) on the bars where the alert fires.
|
|
4173
|
+
* @param title - Name of the condition in the alert dialog.
|
|
4174
|
+
* @param message - Default text of the alert. Default: the title.
|
|
4175
|
+
* @example
|
|
4176
|
+
* ```js
|
|
4177
|
+
* const cross = ta.crossover(close, ta.sma(close, 50));
|
|
4178
|
+
* alertcondition(cross, "Price above SMA 50", "Close crossed above its 50-bar average");
|
|
4179
|
+
* ```
|
|
4180
|
+
*/
|
|
3347
4181
|
export function alertcondition(condition, title, message) {
|
|
3348
4182
|
const c = collector();
|
|
3349
4183
|
const id = `alert${c.alertConfig.length}`;
|
|
@@ -3387,18 +4221,30 @@ function alertImpl(message, freq = 'once_per_bar') {
|
|
|
3387
4221
|
for (let i = 0; i < b.length; i++)
|
|
3388
4222
|
call(i);
|
|
3389
4223
|
}
|
|
3390
|
-
|
|
3391
|
-
export const alert = Object.assign(alertImpl, {
|
|
4224
|
+
const alertMembers = Object.assign(alertImpl, {
|
|
3392
4225
|
freq_all: 'all',
|
|
3393
4226
|
freq_once_per_bar: 'once_per_bar',
|
|
3394
4227
|
freq_once_per_bar_close: 'once_per_bar_close',
|
|
3395
4228
|
});
|
|
4229
|
+
/**
|
|
4230
|
+
* Sends an alert message while the script runs (to the alerts set on the script), with the `alert.freq_*`
|
|
4231
|
+
* constants for how often it may fire.
|
|
4232
|
+
* @example
|
|
4233
|
+
* ```js
|
|
4234
|
+
* eachBar((c) => {
|
|
4235
|
+
* if (c.get(close) > c.get(high, 1)) alert("New high", alert.freq_once_per_bar_close);
|
|
4236
|
+
* });
|
|
4237
|
+
* ```
|
|
4238
|
+
*/
|
|
4239
|
+
export const alert = alertMembers;
|
|
4240
|
+
sameKeys(true);
|
|
3396
4241
|
/** The most messages a run keeps: the newest ones. */
|
|
3397
4242
|
export const MAX_LOG_ENTRIES = 10_000;
|
|
3398
4243
|
let logLineResolver = null;
|
|
3399
4244
|
/**
|
|
3400
|
-
*
|
|
3401
|
-
* `stack`) and gives the line in the script's own source
|
|
4245
|
+
* Host-side: how the host finds the line of the script that called log.*(). Scripts never call it.
|
|
4246
|
+
* @param resolver - Gets the stack of the call (an Error's `stack`) and gives the line in the script's own source;
|
|
4247
|
+
* null (the default): messages have no line.
|
|
3402
4248
|
*/
|
|
3403
4249
|
export function setLogLineResolver(resolver) {
|
|
3404
4250
|
logLineResolver = resolver;
|
|
@@ -3431,14 +4277,7 @@ function logImpl(level, message, args) {
|
|
|
3431
4277
|
if (c.logs.length > MAX_LOG_ENTRIES * 2)
|
|
3432
4278
|
c.logs.splice(0, c.logs.length - MAX_LOG_ENTRIES);
|
|
3433
4279
|
}
|
|
3434
|
-
|
|
3435
|
-
* PineScript `log.info()`, `log.warning()` and `log.error()`: a message for the host's logs panel, made on the current
|
|
3436
|
-
* bar inside eachBar() / strategy.eachBar(), on every bar at the top level of the script (which PineScript runs on
|
|
3437
|
-
* every bar; `message` is then a text or one text per bar, a bar whose text is na makes no message). With arguments,
|
|
3438
|
-
* `message` is a str.format() pattern (`log.info('close {0}', close)`), a Series argument giving its value on the bar.
|
|
3439
|
-
* The messages of a run are in `result.logs`, by bar ({@link MAX_LOG_ENTRIES} newest kept).
|
|
3440
|
-
*/
|
|
3441
|
-
export const log = strictNamespace('log', {
|
|
4280
|
+
const logMembers = strictNamespace('log', {
|
|
3442
4281
|
info(message, ...args) {
|
|
3443
4282
|
logImpl('info', message, args);
|
|
3444
4283
|
},
|
|
@@ -3449,6 +4288,18 @@ export const log = strictNamespace('log', {
|
|
|
3449
4288
|
logImpl('error', message, args);
|
|
3450
4289
|
},
|
|
3451
4290
|
});
|
|
4291
|
+
/**
|
|
4292
|
+
* Messages for the logs panel: `log.info`, `log.warning` and `log.error`. Inside `eachBar()` a call makes a message on
|
|
4293
|
+
* the current bar; at the top level, one message per bar. With arguments the message is a `str.format()` pattern.
|
|
4294
|
+
* @example
|
|
4295
|
+
* ```js
|
|
4296
|
+
* eachBar((c) => {
|
|
4297
|
+
* if (c.get(volume) > 2 * c.get(ta.sma(volume, 20))) log.info("Volume spike: {0}", c.get(volume));
|
|
4298
|
+
* });
|
|
4299
|
+
* ```
|
|
4300
|
+
*/
|
|
4301
|
+
export const log = logMembers;
|
|
4302
|
+
sameKeys(true);
|
|
3452
4303
|
/** The messages of a resumed run calculated from bar `from`: those of the run before on the bars before `from`, then the
|
|
3453
4304
|
* new ones on the bars from `from` (the top-level log calls of a resumed run make them again on every bar). */
|
|
3454
4305
|
function resumedLogs(before, now, from) {
|
|
@@ -3459,10 +4310,19 @@ function resumedLogs(before, now, from) {
|
|
|
3459
4310
|
// ── Convenience re-exports ───────────────────────────────────────────────────
|
|
3460
4311
|
export { Series, BarData };
|
|
3461
4312
|
export { STRATEGY_DEFAULTS } from '../strategy/index.js';
|
|
3462
|
-
/** PineScript `math.*`; `math.round_to_mintick(x)` uses `syminfo.mintick` of the chart context. */
|
|
3463
4313
|
const { saveRandom: _saveRandom, restoreRandom: _restoreRandom, ...mathScript } = mathCore;
|
|
3464
4314
|
void _saveRandom;
|
|
3465
4315
|
void _restoreRandom;
|
|
4316
|
+
/**
|
|
4317
|
+
* Math functions and constants for numbers and Series: rounding, min and max, powers and logarithms, trigonometry,
|
|
4318
|
+
* random numbers, `math.pi`... A Series argument gives a Series, numbers give a number. `math.round_to_mintick`
|
|
4319
|
+
* uses the symbol's tick size.
|
|
4320
|
+
* @example
|
|
4321
|
+
* ```js
|
|
4322
|
+
* const range = math.abs(close.sub(open));
|
|
4323
|
+
* plot(math.round(ta.sma(range, 10), 2), "Body");
|
|
4324
|
+
* ```
|
|
4325
|
+
*/
|
|
3466
4326
|
export const math = strictNamespace('math', {
|
|
3467
4327
|
...mathScript,
|
|
3468
4328
|
// the generators start again on each run: a resumed run would draw other numbers (#206)
|
|
@@ -3475,6 +4335,91 @@ export const math = strictNamespace('math', {
|
|
|
3475
4335
|
return number instanceof Series ? mathCore.round_to_mintick(number, tick) : mathCore.round_to_mintick(number, tick);
|
|
3476
4336
|
}),
|
|
3477
4337
|
});
|
|
3478
|
-
|
|
4338
|
+
// ── calc: plain-English names ────────────────────────────────────────────────
|
|
4339
|
+
/** A number as a Series of the bars of the run. */
|
|
4340
|
+
const asSeries = (v) => (typeof v === 'number' ? Series.constant(ctxBars, v) : v);
|
|
4341
|
+
/** The kinds of `calc.average()`. */
|
|
4342
|
+
const AVERAGE_KINDS = {
|
|
4343
|
+
simple: (s, n) => taSeries.sma(s, n),
|
|
4344
|
+
exponential: (s, n) => taSeries.ema(s, n),
|
|
4345
|
+
weighted: (s, n) => taSeries.wma(s, n),
|
|
4346
|
+
smoothed: (s, n) => taSeries.rma(s, n),
|
|
4347
|
+
hull: (s, n) => taSeries.hma(s, n),
|
|
4348
|
+
'volume-weighted': (s, n) => ta.vwma(s, n),
|
|
4349
|
+
};
|
|
4350
|
+
function checkLength(fn, length) {
|
|
4351
|
+
if (typeof length !== 'number' || !Number.isInteger(length) || length < 1) {
|
|
4352
|
+
throw new ScriptError(`calc.${fn}(): the length is a whole number of bars, 1 or more, got ${shown(length)}.`);
|
|
4353
|
+
}
|
|
4354
|
+
return length;
|
|
4355
|
+
}
|
|
4356
|
+
/** The conditions of `calc.all()` / `calc.any()` as Series; at least one is needed. */
|
|
4357
|
+
function conditionsOf(name, conditions) {
|
|
4358
|
+
if (!conditions.length)
|
|
4359
|
+
throw new ScriptError(`${name}(): give at least one condition, e.g. ${name}(close.gt(open), volume.gt(0)).`);
|
|
4360
|
+
return conditions.map(asSeries);
|
|
4361
|
+
}
|
|
4362
|
+
const calcMembers = strictNamespace('calc', outsideBarLoops({
|
|
4363
|
+
/** Moving average of the last `length` values: kind 'simple' (default), 'exponential', 'weighted', 'smoothed', 'hull' or 'volume-weighted'. */
|
|
4364
|
+
average(source, length, kind = 'simple') {
|
|
4365
|
+
const fn = AVERAGE_KINDS[kind];
|
|
4366
|
+
if (!fn)
|
|
4367
|
+
throw new ScriptError(`calc.average(): the kind is one of ${Object.keys(AVERAGE_KINDS).map((k) => `'${k}'`).join(', ')}, got ${shown(kind)}.`);
|
|
4368
|
+
return fn(asSeries(source), checkLength('average', length));
|
|
4369
|
+
},
|
|
4370
|
+
/** 1 on the bar where `a` crosses above `b`. */
|
|
4371
|
+
crossesAbove: (a, b) => ta.crossover(asSeries(a), b),
|
|
4372
|
+
/** 1 on the bar where `a` crosses below `b`. */
|
|
4373
|
+
crossesBelow: (a, b) => ta.crossunder(asSeries(a), b),
|
|
4374
|
+
/** 1 on the bar where `a` and `b` cross, either way. */
|
|
4375
|
+
crosses: (a, b) => ta.cross(asSeries(a), asSeries(b)),
|
|
4376
|
+
/** 1 where `a` is above `b`. */
|
|
4377
|
+
above: (a, b) => asSeries(a).gt(b),
|
|
4378
|
+
/** 1 where `a` is below `b`. */
|
|
4379
|
+
below: (a, b) => asSeries(a).lt(b),
|
|
4380
|
+
/** 1 where `value` is between `low` and `high` (both included). */
|
|
4381
|
+
between: (value, lowLimit, highLimit) => asSeries(value).gte(lowLimit).and(asSeries(value).lte(highLimit)),
|
|
4382
|
+
/** The value `bars` bars before (1: the previous bar). */
|
|
4383
|
+
previous: (source, bars = 1) => asSeries(source).offset(checkLength('previous', bars)),
|
|
4384
|
+
/** The difference with the value `bars` bars before. */
|
|
4385
|
+
change: (source, bars = 1) => taSeries.change(asSeries(source), checkLength('change', bars)),
|
|
4386
|
+
/** The change in percent since `bars` bars before. */
|
|
4387
|
+
percentChange: (source, bars = 1) => {
|
|
4388
|
+
const s = asSeries(source);
|
|
4389
|
+
const before = s.offset(checkLength('percentChange', bars));
|
|
4390
|
+
return s.sub(before).div(before).mul(100);
|
|
4391
|
+
},
|
|
4392
|
+
/** The highest value of the last `length` bars. */
|
|
4393
|
+
highest: (source, length) => ta.highest(asSeries(source), checkLength('highest', length)),
|
|
4394
|
+
/** The lowest value of the last `length` bars. */
|
|
4395
|
+
lowest: (source, length) => ta.lowest(asSeries(source), checkLength('lowest', length)),
|
|
4396
|
+
/** 1 when the value rose on each of the last `bars` bars. */
|
|
4397
|
+
isRising: (source, bars = 1) => taSeries.rising(asSeries(source), checkLength('isRising', bars)),
|
|
4398
|
+
/** 1 when the value fell on each of the last `bars` bars. */
|
|
4399
|
+
isFalling: (source, bars = 1) => taSeries.falling(asSeries(source), checkLength('isFalling', bars)),
|
|
4400
|
+
/** Standard deviation of the last `length` values. */
|
|
4401
|
+
standardDeviation: (source, length) => taSeries.stdev(asSeries(source), checkLength('standardDeviation', length)),
|
|
4402
|
+
/** `whenTrue` where the condition holds, else `whenFalse`. */
|
|
4403
|
+
ifElse: (condition, whenTrue, whenFalse) => asSeries(condition).iff(whenTrue, whenFalse),
|
|
4404
|
+
/** 1 where every condition holds. */
|
|
4405
|
+
all: (...conditions) => conditionsOf('calc.all', conditions).reduce((x, y) => x.and(y)),
|
|
4406
|
+
/** 1 where one of the conditions holds. */
|
|
4407
|
+
any: (...conditions) => conditionsOf('calc.any', conditions).reduce((x, y) => x.or(y)),
|
|
4408
|
+
}, 'calc'));
|
|
4409
|
+
/**
|
|
4410
|
+
* Plain-English names for the most used calculations (`calc.average`, `calc.crossesAbove`...), beside the `ta.*` ones.
|
|
4411
|
+
* They take Series or numbers and give a Series; a condition gives 1 where true and 0 where false.
|
|
4412
|
+
*/
|
|
4413
|
+
export const calc = calcMembers;
|
|
4414
|
+
sameKeys(true);
|
|
4415
|
+
/**
|
|
4416
|
+
* Comparisons of two numbers with a tolerance of 1e-10 (`compare.eq(0.1 + 0.2, 0.3)` is true), for the plain numbers
|
|
4417
|
+
* of a bar loop.
|
|
4418
|
+
*/
|
|
4419
|
+
export const compare = compareCore;
|
|
3479
4420
|
export { isInputActive } from '../runtime/input-active.js';
|
|
4421
|
+
// ── defineIndicator ─────────────────────────────────────────────────────────
|
|
4422
|
+
export { defineIndicator, } from './define.js';
|
|
4423
|
+
export { formula, evaluateFormula, FORMULA_FUNCTIONS } from './formula.js';
|
|
4424
|
+
export { defineIndicatorFromJson, indicatorBodyFromJson, checkIndicatorJson, } from './json.js';
|
|
3480
4425
|
//# sourceMappingURL=index.js.map
|