oakscriptjs 0.23.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -1
- package/bin/oakscript.mjs +10 -3
- package/dist/cjs/box/index.d.ts +348 -289
- package/dist/cjs/box/index.d.ts.map +1 -1
- package/dist/cjs/box/index.js.map +2 -2
- package/dist/cjs/check/node.d.ts.map +1 -1
- package/dist/cjs/check/node.js +1 -0
- package/dist/cjs/check/node.js.map +2 -2
- package/dist/cjs/check/preview.d.ts +31 -0
- package/dist/cjs/check/preview.d.ts.map +1 -0
- package/dist/cjs/check/preview.js +303 -0
- package/dist/cjs/check/preview.js.map +7 -0
- package/dist/cjs/color/index.d.ts +11 -11
- package/dist/cjs/color/index.js.map +1 -1
- package/dist/cjs/color/parse.d.ts +2 -0
- package/dist/cjs/color/parse.d.ts.map +1 -1
- package/dist/cjs/color/parse.js +6 -0
- package/dist/cjs/color/parse.js.map +2 -2
- package/dist/cjs/compare/index.d.ts +76 -12
- package/dist/cjs/compare/index.d.ts.map +1 -1
- package/dist/cjs/compare/index.js.map +2 -2
- package/dist/cjs/drawing/registry.d.ts +28 -5
- package/dist/cjs/drawing/registry.d.ts.map +1 -1
- package/dist/cjs/drawing/registry.js +14 -0
- package/dist/cjs/drawing/registry.js.map +2 -2
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/label/index.d.ts +265 -187
- package/dist/cjs/label/index.d.ts.map +1 -1
- package/dist/cjs/label/index.js +1 -1
- package/dist/cjs/label/index.js.map +2 -2
- package/dist/cjs/line/index.d.ts +247 -207
- package/dist/cjs/line/index.d.ts.map +1 -1
- package/dist/cjs/line/index.js.map +2 -2
- package/dist/cjs/linefill/index.d.ts +61 -89
- package/dist/cjs/linefill/index.d.ts.map +1 -1
- package/dist/cjs/linefill/index.js.map +2 -2
- package/dist/cjs/math/index.d.ts +49 -40
- package/dist/cjs/math/index.d.ts.map +1 -1
- package/dist/cjs/math/index.js.map +2 -2
- package/dist/cjs/polyline/index.d.ts +57 -78
- package/dist/cjs/polyline/index.d.ts.map +1 -1
- package/dist/cjs/polyline/index.js.map +2 -2
- package/dist/cjs/runtime/input-active.d.ts +2 -2
- package/dist/cjs/runtime/input-active.js.map +1 -1
- package/dist/cjs/runtime/series.d.ts +241 -161
- package/dist/cjs/runtime/series.d.ts.map +1 -1
- package/dist/cjs/runtime/series.js +223 -127
- package/dist/cjs/runtime/series.js.map +2 -2
- package/dist/cjs/script/api/alert.d.ts +37 -0
- package/dist/cjs/script/api/alert.d.ts.map +1 -0
- package/dist/cjs/script/api/alert.js +17 -0
- package/dist/cjs/script/api/alert.js.map +7 -0
- package/dist/cjs/script/api/calc.d.ts +232 -0
- package/dist/cjs/script/api/calc.d.ts.map +1 -0
- package/dist/cjs/script/api/calc.js +17 -0
- package/dist/cjs/script/api/calc.js.map +7 -0
- package/dist/cjs/script/api/color.d.ts +213 -0
- package/dist/cjs/script/api/color.d.ts.map +1 -0
- package/dist/cjs/script/api/color.js +17 -0
- package/dist/cjs/script/api/color.js.map +7 -0
- package/dist/cjs/script/api/context.d.ts +764 -0
- package/dist/cjs/script/api/context.d.ts.map +1 -0
- package/dist/cjs/script/api/context.js +17 -0
- package/dist/cjs/script/api/context.js.map +7 -0
- package/dist/cjs/script/api/log.d.ts +58 -0
- package/dist/cjs/script/api/log.d.ts.map +1 -0
- package/dist/cjs/script/api/log.js +17 -0
- package/dist/cjs/script/api/log.js.map +7 -0
- package/dist/cjs/script/api/strategy.d.ts +391 -0
- package/dist/cjs/script/api/strategy.d.ts.map +1 -0
- package/dist/cjs/script/api/strategy.js +17 -0
- package/dist/cjs/script/api/strategy.js.map +7 -0
- package/dist/cjs/script/api/ta.d.ts +1012 -0
- package/dist/cjs/script/api/ta.d.ts.map +1 -0
- package/dist/cjs/script/api/ta.js +17 -0
- package/dist/cjs/script/api/ta.js.map +7 -0
- package/dist/cjs/script/api/table.d.ts +479 -0
- package/dist/cjs/script/api/table.d.ts.map +1 -0
- package/dist/cjs/script/api/table.js +17 -0
- package/dist/cjs/script/api/table.js.map +7 -0
- package/dist/cjs/script/constants.d.ts +228 -83
- package/dist/cjs/script/constants.d.ts.map +1 -1
- package/dist/cjs/script/constants.js +87 -0
- package/dist/cjs/script/constants.js.map +2 -2
- package/dist/cjs/script/define.d.ts +94 -0
- package/dist/cjs/script/define.d.ts.map +1 -0
- package/dist/cjs/script/define.js +127 -0
- package/dist/cjs/script/define.js.map +7 -0
- package/dist/cjs/script/drawing-args.d.ts.map +1 -1
- package/dist/cjs/script/drawing-args.js +1 -1
- package/dist/cjs/script/drawing-args.js.map +2 -2
- package/dist/cjs/script/formula.d.ts +53 -0
- package/dist/cjs/script/formula.d.ts.map +1 -0
- package/dist/cjs/script/formula.js +402 -0
- package/dist/cjs/script/formula.js.map +7 -0
- package/dist/cjs/script/globals.d.ts +10 -0
- package/dist/cjs/script/globals.d.ts.map +1 -1
- package/dist/cjs/script/globals.js.map +1 -1
- package/dist/cjs/script/index.d.ts +1065 -1006
- package/dist/cjs/script/index.d.ts.map +1 -1
- package/dist/cjs/script/index.js +532 -61
- package/dist/cjs/script/index.js.map +3 -3
- package/dist/cjs/script/json.d.ts +117 -0
- package/dist/cjs/script/json.d.ts.map +1 -0
- package/dist/cjs/script/json.js +321 -0
- package/dist/cjs/script/json.js.map +7 -0
- package/dist/cjs/security/other.d.ts +8 -3
- package/dist/cjs/security/other.d.ts.map +1 -1
- package/dist/cjs/security/other.js +23 -6
- package/dist/cjs/security/other.js.map +2 -2
- package/dist/cjs/str/index.d.ts +50 -75
- package/dist/cjs/str/index.d.ts.map +1 -1
- package/dist/cjs/str/index.js +2 -2
- package/dist/cjs/str/index.js.map +2 -2
- package/dist/cjs/strategy/index.d.ts +102 -1
- package/dist/cjs/strategy/index.d.ts.map +1 -1
- package/dist/cjs/strategy/index.js.map +2 -2
- package/dist/cjs/table/index.d.ts +330 -49
- package/dist/cjs/table/index.d.ts.map +1 -1
- package/dist/cjs/table/index.js +55 -27
- package/dist/cjs/table/index.js.map +2 -2
- package/dist/cjs/text/index.d.ts +12 -14
- package/dist/cjs/text/index.d.ts.map +1 -1
- package/dist/cjs/text/index.js.map +2 -2
- package/dist/cjs/types/index.d.ts +15 -8
- package/dist/cjs/types/index.d.ts.map +1 -1
- package/dist/cjs/types/index.js +12 -3
- package/dist/cjs/types/index.js.map +2 -2
- package/dist/esm/box/index.d.ts +348 -289
- package/dist/esm/box/index.d.ts.map +1 -1
- package/dist/esm/box/index.js +276 -276
- package/dist/esm/box/index.js.map +1 -1
- package/dist/esm/check/node.d.ts.map +1 -1
- package/dist/esm/check/node.js +1 -0
- package/dist/esm/check/node.js.map +1 -1
- package/dist/esm/check/preview.d.ts +31 -0
- package/dist/esm/check/preview.d.ts.map +1 -0
- package/dist/esm/check/preview.js +296 -0
- package/dist/esm/check/preview.js.map +1 -0
- package/dist/esm/color/index.d.ts +11 -11
- package/dist/esm/color/index.js +11 -11
- package/dist/esm/color/parse.d.ts +2 -0
- package/dist/esm/color/parse.d.ts.map +1 -1
- package/dist/esm/color/parse.js +7 -0
- package/dist/esm/color/parse.js.map +1 -1
- package/dist/esm/compare/index.d.ts +76 -12
- package/dist/esm/compare/index.d.ts.map +1 -1
- package/dist/esm/compare/index.js +76 -12
- package/dist/esm/compare/index.js.map +1 -1
- package/dist/esm/drawing/registry.d.ts +28 -5
- package/dist/esm/drawing/registry.d.ts.map +1 -1
- package/dist/esm/drawing/registry.js +39 -3
- package/dist/esm/drawing/registry.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/label/index.d.ts +265 -187
- package/dist/esm/label/index.d.ts.map +1 -1
- package/dist/esm/label/index.js +207 -177
- package/dist/esm/label/index.js.map +1 -1
- package/dist/esm/line/index.d.ts +247 -207
- package/dist/esm/line/index.d.ts.map +1 -1
- package/dist/esm/line/index.js +202 -194
- package/dist/esm/line/index.js.map +1 -1
- package/dist/esm/linefill/index.d.ts +61 -89
- package/dist/esm/linefill/index.d.ts.map +1 -1
- package/dist/esm/linefill/index.js +61 -89
- package/dist/esm/linefill/index.js.map +1 -1
- package/dist/esm/math/index.d.ts +49 -40
- package/dist/esm/math/index.d.ts.map +1 -1
- package/dist/esm/math/index.js +22 -9
- package/dist/esm/math/index.js.map +1 -1
- package/dist/esm/polyline/index.d.ts +57 -78
- package/dist/esm/polyline/index.d.ts.map +1 -1
- package/dist/esm/polyline/index.js +57 -78
- package/dist/esm/polyline/index.js.map +1 -1
- package/dist/esm/runtime/input-active.d.ts +2 -2
- package/dist/esm/runtime/input-active.js +2 -2
- package/dist/esm/runtime/series.d.ts +241 -161
- package/dist/esm/runtime/series.d.ts.map +1 -1
- package/dist/esm/runtime/series.js +241 -161
- package/dist/esm/runtime/series.js.map +1 -1
- package/dist/esm/script/api/alert.d.ts +37 -0
- package/dist/esm/script/api/alert.d.ts.map +1 -0
- package/dist/esm/script/api/alert.js +7 -0
- package/dist/esm/script/api/alert.js.map +1 -0
- package/dist/esm/script/api/calc.d.ts +232 -0
- package/dist/esm/script/api/calc.d.ts.map +1 -0
- package/dist/esm/script/api/calc.js +6 -0
- package/dist/esm/script/api/calc.js.map +1 -0
- package/dist/esm/script/api/color.d.ts +213 -0
- package/dist/esm/script/api/color.d.ts.map +1 -0
- package/dist/esm/script/api/color.js +6 -0
- package/dist/esm/script/api/color.js.map +1 -0
- package/dist/esm/script/api/context.d.ts +764 -0
- package/dist/esm/script/api/context.d.ts.map +1 -0
- package/dist/esm/script/api/context.js +7 -0
- package/dist/esm/script/api/context.js.map +1 -0
- package/dist/esm/script/api/log.d.ts +58 -0
- package/dist/esm/script/api/log.d.ts.map +1 -0
- package/dist/esm/script/api/log.js +6 -0
- package/dist/esm/script/api/log.js.map +1 -0
- package/dist/esm/script/api/strategy.d.ts +391 -0
- package/dist/esm/script/api/strategy.d.ts.map +1 -0
- package/dist/esm/script/api/strategy.js +7 -0
- package/dist/esm/script/api/strategy.js.map +1 -0
- package/dist/esm/script/api/ta.d.ts +1012 -0
- package/dist/esm/script/api/ta.d.ts.map +1 -0
- package/dist/esm/script/api/ta.js +6 -0
- package/dist/esm/script/api/ta.js.map +1 -0
- package/dist/esm/script/api/table.d.ts +479 -0
- package/dist/esm/script/api/table.d.ts.map +1 -0
- package/dist/esm/script/api/table.js +7 -0
- package/dist/esm/script/api/table.js.map +1 -0
- package/dist/esm/script/constants.d.ts +228 -83
- package/dist/esm/script/constants.d.ts.map +1 -1
- package/dist/esm/script/constants.js +110 -24
- package/dist/esm/script/constants.js.map +1 -1
- package/dist/esm/script/define.d.ts +94 -0
- package/dist/esm/script/define.d.ts.map +1 -0
- package/dist/esm/script/define.js +136 -0
- package/dist/esm/script/define.js.map +1 -0
- package/dist/esm/script/drawing-args.d.ts.map +1 -1
- package/dist/esm/script/drawing-args.js +2 -1
- package/dist/esm/script/drawing-args.js.map +1 -1
- package/dist/esm/script/formula.d.ts +53 -0
- package/dist/esm/script/formula.d.ts.map +1 -0
- package/dist/esm/script/formula.js +408 -0
- package/dist/esm/script/formula.js.map +1 -0
- package/dist/esm/script/globals.d.ts +10 -0
- package/dist/esm/script/globals.d.ts.map +1 -1
- package/dist/esm/script/globals.js.map +1 -1
- package/dist/esm/script/index.d.ts +1065 -1006
- package/dist/esm/script/index.d.ts.map +1 -1
- package/dist/esm/script/index.js +1099 -153
- package/dist/esm/script/index.js.map +1 -1
- package/dist/esm/script/json.d.ts +117 -0
- package/dist/esm/script/json.d.ts.map +1 -0
- package/dist/esm/script/json.js +375 -0
- package/dist/esm/script/json.js.map +1 -0
- package/dist/esm/security/other.d.ts +8 -3
- package/dist/esm/security/other.d.ts.map +1 -1
- package/dist/esm/security/other.js +45 -10
- package/dist/esm/security/other.js.map +1 -1
- package/dist/esm/str/index.d.ts +50 -75
- package/dist/esm/str/index.d.ts.map +1 -1
- package/dist/esm/str/index.js +51 -76
- package/dist/esm/str/index.js.map +1 -1
- package/dist/esm/strategy/index.d.ts +102 -1
- package/dist/esm/strategy/index.d.ts.map +1 -1
- package/dist/esm/strategy/index.js +1 -1
- package/dist/esm/strategy/index.js.map +1 -1
- package/dist/esm/table/index.d.ts +330 -49
- package/dist/esm/table/index.d.ts.map +1 -1
- package/dist/esm/table/index.js +372 -61
- package/dist/esm/table/index.js.map +1 -1
- package/dist/esm/text/index.d.ts +12 -14
- package/dist/esm/text/index.d.ts.map +1 -1
- package/dist/esm/text/index.js +12 -14
- package/dist/esm/text/index.js.map +1 -1
- package/dist/esm/types/index.d.ts +15 -8
- package/dist/esm/types/index.d.ts.map +1 -1
- package/dist/esm/types/index.js +15 -8
- package/dist/esm/types/index.js.map +1 -1
- package/docs/first-indicator.md +152 -0
- package/docs/guide.md +1185 -0
- package/docs/inventory.md +772 -0
- package/docs/no-code.md +207 -0
- package/docs/recipes.md +202 -0
- package/package.json +2 -1
- package/skills/oakscript/SKILL.md +8 -0
- package/skills/oakscript/reference/errors.md +3 -2
- package/skills/oakscript/reference/timeframes-symbols.md +4 -0
- package/src/box/index.ts +348 -289
- package/src/check/node.ts +1 -0
- package/src/check/preview.ts +307 -0
- package/src/color/index.ts +11 -11
- package/src/color/parse.ts +7 -0
- package/src/compare/index.ts +76 -12
- package/src/drawing/registry.ts +44 -5
- package/src/index.ts +1 -1
- package/src/label/index.ts +267 -189
- package/src/line/index.ts +248 -208
- package/src/linefill/index.ts +61 -89
- package/src/math/index.ts +51 -42
- package/src/polyline/index.ts +57 -78
- package/src/runtime/input-active.ts +2 -2
- package/src/runtime/series.ts +243 -163
- package/src/script/api/alert.ts +43 -0
- package/src/script/api/calc.ts +250 -0
- package/src/script/api/color.ts +245 -0
- package/src/script/api/context.ts +944 -0
- package/src/script/api/log.ts +60 -0
- package/src/script/api/strategy.ts +410 -0
- package/src/script/api/ta.ts +1115 -0
- package/src/script/api/table.ts +538 -0
- package/src/script/constants.ts +229 -25
- package/src/script/define.ts +221 -0
- package/src/script/drawing-args.ts +2 -1
- package/src/script/formula.ts +438 -0
- package/src/script/globals.ts +10 -0
- package/src/script/index.ts +1520 -241
- package/src/script/json.ts +457 -0
- package/src/security/other.ts +43 -9
- package/src/str/index.ts +51 -76
- package/src/strategy/index.ts +102 -1
- package/src/table/index.ts +388 -62
- package/src/text/index.ts +12 -14
- package/src/types/index.ts +15 -8
package/src/script/index.ts
CHANGED
|
@@ -75,13 +75,34 @@ import type {
|
|
|
75
75
|
} from '../runtime/types.js';
|
|
76
76
|
import { BarData, Series, MAX_BARS_BACK, historyError } from '../runtime/series.js';
|
|
77
77
|
import * as taSeries from '../ta-series.js';
|
|
78
|
+
import type { TaNamespace } from './api/ta.js';
|
|
79
|
+
import type { StrategyNamespace } from './api/strategy.js';
|
|
80
|
+
import type {
|
|
81
|
+
BarmergeNamespace,
|
|
82
|
+
BarstateNamespace,
|
|
83
|
+
ChartNamespace,
|
|
84
|
+
DividendsNamespace,
|
|
85
|
+
EarningsNamespace,
|
|
86
|
+
RequestNamespace,
|
|
87
|
+
SessionNamespace,
|
|
88
|
+
SplitsNamespace,
|
|
89
|
+
SyminfoNamespace,
|
|
90
|
+
TickerNamespace,
|
|
91
|
+
TimeframeNamespace,
|
|
92
|
+
} from './api/context.js';
|
|
93
|
+
import type { CalcNamespace } from './api/calc.js';
|
|
94
|
+
import type { ColorNamespace } from './api/color.js';
|
|
95
|
+
import type { LogNamespace } from './api/log.js';
|
|
96
|
+
import type { AlertApi } from './api/alert.js';
|
|
97
|
+
import type { TableNamespace } from './api/table.js';
|
|
78
98
|
import { taStep, type BarStep } from '../ta/step.js';
|
|
79
99
|
import * as incremental from './incremental.js';
|
|
80
100
|
import { outerWrites } from './closure-writes.js';
|
|
81
101
|
import * as pineConstants from './constants.js';
|
|
82
102
|
import { drawingNamespace, isPlainObject, namedArguments, unknownArgument } from './drawing-args.js';
|
|
83
103
|
import * as colorCore from '../color/index.js';
|
|
84
|
-
import
|
|
104
|
+
import * as compareCore from '../compare/index.js';
|
|
105
|
+
import { inputColorDefault, isColorText } from '../color/parse.js';
|
|
85
106
|
import { fixnan as fixnanValues, isNA, nz as nzValue } from '../utils/index.js';
|
|
86
107
|
import { externalSource } from '../utils/source-resolver.js';
|
|
87
108
|
import * as lineCore from '../line/index.js';
|
|
@@ -95,6 +116,7 @@ import * as textCore from '../text/index.js';
|
|
|
95
116
|
import * as mathCore from '../math/index.js';
|
|
96
117
|
import {
|
|
97
118
|
createdDrawingKinds,
|
|
119
|
+
droppedDrawings,
|
|
98
120
|
resetDrawings,
|
|
99
121
|
restoreDrawingCheckpoint,
|
|
100
122
|
restoreDrawingState,
|
|
@@ -110,11 +132,23 @@ import {
|
|
|
110
132
|
export { holdDrawing, releaseDrawing, type DrawingVariable } from '../drawing/registry.js';
|
|
111
133
|
|
|
112
134
|
/**
|
|
113
|
-
* A
|
|
114
|
-
*
|
|
115
|
-
*
|
|
135
|
+
* A variable that holds one drawing (a line, label, box...) from bar to bar and keeps it alive: the object it holds is
|
|
136
|
+
* never deleted by the `max_*_count` limit of the script. Use it to create one object and move it, instead of a new
|
|
137
|
+
* object on each bar. Assigning another object (or `undefined` for na) releases the one before, which the limit can
|
|
138
|
+
* delete again. Declare it in the script body (outside the bar loops), then read and write `.value` in a bar loop.
|
|
139
|
+
* @param initial - The object held from the start. Default: none (`.value` is `undefined`).
|
|
140
|
+
* @returns A box whose `.value` is the held object, or `undefined`.
|
|
141
|
+
* @example
|
|
142
|
+
* ```js
|
|
143
|
+
* const level = varDrawing();
|
|
144
|
+
* eachBar((c) => {
|
|
145
|
+
* if (c.i === c.n - 1) level.value = line.new(c.i - 20, c.close, c.i, c.close, { color: color.orange });
|
|
146
|
+
* });
|
|
147
|
+
* ```
|
|
116
148
|
*/
|
|
117
|
-
|
|
149
|
+
// Without an initial object the kind is not known: `.value` is any drawing, so `line.delete(v.value)` checks.
|
|
150
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
151
|
+
export function varDrawing<T extends object = any>(initial?: T): DrawingVariable<T> {
|
|
118
152
|
const box = persist<T | undefined>(initial ? holdDrawing(initial) : undefined);
|
|
119
153
|
return {
|
|
120
154
|
get value() {
|
|
@@ -166,7 +200,16 @@ import { sessionPeriods, type SessionPeriods } from '../session/context.js';
|
|
|
166
200
|
|
|
167
201
|
/** Everything one run of a script produced. */
|
|
168
202
|
export interface ScriptRunResult {
|
|
169
|
-
metadata: {
|
|
203
|
+
metadata: {
|
|
204
|
+
title: string;
|
|
205
|
+
shortTitle?: string;
|
|
206
|
+
overlay: boolean;
|
|
207
|
+
precision?: number;
|
|
208
|
+
format?: string;
|
|
209
|
+
scale?: 'right' | 'left' | 'none';
|
|
210
|
+
/** indicator(..., { pane }) when the script gives it (not PineScript); `overlay` is the pane it gave. */
|
|
211
|
+
pane?: 'price' | 'separate' | 'auto';
|
|
212
|
+
};
|
|
170
213
|
inputConfig: InputConfig[];
|
|
171
214
|
plotConfig: PlotConfig[];
|
|
172
215
|
hlineConfig: HLineConfig[];
|
|
@@ -203,6 +246,11 @@ export interface ScriptRunResult {
|
|
|
203
246
|
/** The script read `chart.left_visible_bar_time` or `chart.right_visible_bar_time`: it has to be calculated again when
|
|
204
247
|
* the visible range of the chart changes. */
|
|
205
248
|
usesVisibleRange: boolean;
|
|
249
|
+
/**
|
|
250
|
+
* Things the run did that a script usually does not mean, in plain words: drawings deleted because there were more
|
|
251
|
+
* than the maximum count (`indicator(max_labels_count)`...). Empty when there is nothing to say.
|
|
252
|
+
*/
|
|
253
|
+
warnings: string[];
|
|
206
254
|
}
|
|
207
255
|
|
|
208
256
|
export interface AlertConditionConfig {
|
|
@@ -283,6 +331,16 @@ interface Collector {
|
|
|
283
331
|
hasAlertFunction: boolean;
|
|
284
332
|
usesVisibleRange: boolean;
|
|
285
333
|
strategy?: StrategyRun;
|
|
334
|
+
/** Strict mode (`ScriptOptions.strict`): mistakes are errors. */
|
|
335
|
+
strict: boolean;
|
|
336
|
+
/** indicator(..., { pane: 'auto' }): the pane is chosen from the plotted values at the end of the run. */
|
|
337
|
+
paneAuto?: boolean;
|
|
338
|
+
/** indicator(..., { pane }) as given. */
|
|
339
|
+
pane?: 'price' | 'separate' | 'auto';
|
|
340
|
+
/** Plot ids taken (`ScriptOptions.plotIds` 'title'). */
|
|
341
|
+
plotIdsTaken?: Set<string>;
|
|
342
|
+
/** Plots that took a colour of the palette so far. */
|
|
343
|
+
paletteUsed?: number;
|
|
286
344
|
}
|
|
287
345
|
|
|
288
346
|
/** State of the strategy of the current run. */
|
|
@@ -311,8 +369,9 @@ function collector(): Collector {
|
|
|
311
369
|
return ctx;
|
|
312
370
|
}
|
|
313
371
|
|
|
314
|
-
function freshCollector(inputValues: Record<string, unknown
|
|
372
|
+
function freshCollector(inputValues: Record<string, unknown>, strict = false): Collector {
|
|
315
373
|
return {
|
|
374
|
+
strict,
|
|
316
375
|
title: 'Untitled',
|
|
317
376
|
overlay: false,
|
|
318
377
|
inputValues,
|
|
@@ -358,6 +417,159 @@ function slugId(title: string | undefined, fallback: string, taken: Set<string>)
|
|
|
358
417
|
return id;
|
|
359
418
|
}
|
|
360
419
|
|
|
420
|
+
/** A value as it is written in a script, for messages. */
|
|
421
|
+
function shown(v: unknown): string {
|
|
422
|
+
if (typeof v === 'string') return JSON.stringify(v);
|
|
423
|
+
if (typeof v === 'number' || typeof v === 'boolean' || v === null || v === undefined) return String(v);
|
|
424
|
+
return Array.isArray(v) ? 'a list' : typeof v === 'object' ? 'an object' : typeof v;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Up to three of `names` close to `name` (spelling mistakes), closest first. */
|
|
428
|
+
function closeNames(name: string, names: readonly string[]): string[] {
|
|
429
|
+
const bare = (x: string) => x.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
430
|
+
const same = names.filter((k) => bare(k) === bare(name));
|
|
431
|
+
if (same.length) return same;
|
|
432
|
+
const n = name.toLowerCase();
|
|
433
|
+
const dist = (a: string, b: string): number => {
|
|
434
|
+
const row = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
435
|
+
for (let i = 1; i <= a.length; i++) {
|
|
436
|
+
let diag = row[0]!;
|
|
437
|
+
row[0] = i;
|
|
438
|
+
for (let j = 1; j <= b.length; j++) {
|
|
439
|
+
const up = row[j]!;
|
|
440
|
+
row[j] = Math.min(up + 1, row[j - 1]! + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
441
|
+
diag = up;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
return row[b.length]!;
|
|
445
|
+
};
|
|
446
|
+
return names
|
|
447
|
+
.map((k) => ({ k, d: dist(n, k.toLowerCase()) }))
|
|
448
|
+
.filter(({ k, d }) => d <= Math.max(2, Math.floor(name.length / 3)) || k.toLowerCase().includes(n) || n.includes(k.toLowerCase()))
|
|
449
|
+
.sort((a, b) => a.d - b.d)
|
|
450
|
+
.slice(0, 3)
|
|
451
|
+
.map(({ k }) => k);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** Strict mode: every input value given by the host has a name the script declares. */
|
|
455
|
+
function checkInputNames(c: Collector, inputs: Record<string, unknown>): void {
|
|
456
|
+
const names = c.inputConfig.map((i) => i.id);
|
|
457
|
+
for (const key of Object.keys(inputs)) {
|
|
458
|
+
if (c.inputIds.has(key)) continue;
|
|
459
|
+
const near = closeNames(key, names);
|
|
460
|
+
throw new ScriptError(
|
|
461
|
+
`There is no input "${key}".` + (near.length ? ` Did you mean "${near.join('", "')}"?` : '') +
|
|
462
|
+
(names.length ? ` The inputs are: ${names.join(', ')}.` : ' The script has no inputs.')
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** Strict mode: the value the host gives an input has its type, range and options. */
|
|
468
|
+
function checkInputValue(config: InputConfig, id: string, value: unknown): void {
|
|
469
|
+
const name = config.title ? `"${config.title}" (${id})` : `"${id}"`;
|
|
470
|
+
const fail = (why: string): never => {
|
|
471
|
+
throw new ScriptError(`Input ${name}: ${why}`);
|
|
472
|
+
};
|
|
473
|
+
switch (config.type) {
|
|
474
|
+
case 'int':
|
|
475
|
+
case 'float':
|
|
476
|
+
case 'price':
|
|
477
|
+
case 'time':
|
|
478
|
+
if (typeof value !== 'number' || Number.isNaN(value)) fail(`${shown(value)} is not a number.`);
|
|
479
|
+
if (config.type === 'int' && !Number.isInteger(value)) fail(`${value} is not a whole number.`);
|
|
480
|
+
if (config.min !== undefined && (value as number) < config.min) fail(`${value} is below the minimum, ${config.min}.`);
|
|
481
|
+
if (config.max !== undefined && (value as number) > config.max) fail(`${value} is above the maximum, ${config.max}.`);
|
|
482
|
+
break;
|
|
483
|
+
case 'bool':
|
|
484
|
+
if (typeof value !== 'boolean') fail(`${shown(value)} is not true or false.`);
|
|
485
|
+
break;
|
|
486
|
+
case 'color':
|
|
487
|
+
if (!isColorText(value)) fail(`${shown(value)} is not a colour. Write it as "#ff0000" or "rgba(255, 0, 0, 0.5)".`);
|
|
488
|
+
break;
|
|
489
|
+
case 'source':
|
|
490
|
+
if (typeof value !== 'string' || (!SOURCES[value] && !externalSource(value))) {
|
|
491
|
+
fail(`${shown(value)} is not a price source. The sources are: ${Object.keys(SOURCES).join(', ')}.`);
|
|
492
|
+
}
|
|
493
|
+
break;
|
|
494
|
+
default:
|
|
495
|
+
if (typeof value !== 'string') fail(`${shown(value)} is not a text.`);
|
|
496
|
+
}
|
|
497
|
+
if (config.options && !config.options.includes(value as string | number)) {
|
|
498
|
+
fail(`${shown(value)} is not one of the choices: ${config.options.map(shown).join(', ')}.`);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** Strict mode: the named options of a declaration call are known and its colours are colours. */
|
|
503
|
+
function checkOptions(fn: string, options: object | undefined, keys: readonly string[], colorKeys: readonly string[] = ['color']): void {
|
|
504
|
+
if (!ctx?.strict || options === undefined) return;
|
|
505
|
+
if (!isPlainObject(options)) throw new ScriptError(`${fn}(): the options are an object, e.g. { color: color.red }.`);
|
|
506
|
+
for (const [key, v] of Object.entries(options)) {
|
|
507
|
+
if (!keys.includes(key)) {
|
|
508
|
+
const near = closeNames(key, keys);
|
|
509
|
+
throw new ScriptError(
|
|
510
|
+
`${fn}(): there is no option "${key}".` + (near.length ? ` Did you mean "${near.join('", "')}"?` : '') +
|
|
511
|
+
` The options are: ${keys.join(', ')}.`
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
if (colorKeys.includes(key)) checkColor(`${fn}(): the ${key}`, v);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** Strict mode: a colour argument (a colour or per-bar colours; na entries are allowed) holds colours only. */
|
|
519
|
+
function checkColor(what: string, v: unknown): void {
|
|
520
|
+
if (v === undefined || v === null) return;
|
|
521
|
+
const bad = Array.isArray(v) ? v.find((x) => x !== undefined && x !== null && x !== '' && !isColorText(x)) : isColorText(v) ? undefined : v;
|
|
522
|
+
if (bad !== undefined) {
|
|
523
|
+
const name = typeof bad === 'string' ? bad.trim().toLowerCase() : '';
|
|
524
|
+
if (/^[a-z]+$/.test(name) && typeof (colorCore as Record<string, unknown>)[name] === 'string') {
|
|
525
|
+
throw new ScriptError(`${what} ${shown(bad)} is a colour name: write color.${name} (without quotes).`);
|
|
526
|
+
}
|
|
527
|
+
throw new ScriptError(`${what} ${shown(bad)} is not a colour. Write a colour as color.red, "#ff0000" or "rgba(255, 0, 0, 0.5)".`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** The warnings of the run that ends (see `ScriptRunResult.warnings`). */
|
|
532
|
+
function runWarnings(): string[] {
|
|
533
|
+
const out: string[] = [];
|
|
534
|
+
const option: Record<string, string> = { line: 'max_lines_count', label: 'max_labels_count', box: 'max_boxes_count', polyline: 'max_polylines_count', linefill: 'max_lines_count' };
|
|
535
|
+
for (const [kind, n] of Object.entries(droppedDrawings())) {
|
|
536
|
+
if (!n || kind === 'table') continue;
|
|
537
|
+
out.push(
|
|
538
|
+
`${n} ${kind}${n > 1 ? 's were' : ' was'} deleted because the script made more than the maximum number of ${kind}s; ` +
|
|
539
|
+
`the oldest go first. To keep more, raise ${option[kind]} in indicator(), e.g. indicator("...", { ${option[kind]}: 500 }).`
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
return out;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* indicator(..., { pane: 'auto' }): the plots belong on the price chart when nine values in ten (all plots together) are
|
|
547
|
+
* within the price range of the bars, widened by a quarter on each side (plots with display 'none' do not count); a script
|
|
548
|
+
* without plots goes on the price chart.
|
|
549
|
+
*/
|
|
550
|
+
function plotsOnPrices(c: Collector): boolean {
|
|
551
|
+
const b = ctxBars.bars;
|
|
552
|
+
let lo = Infinity;
|
|
553
|
+
let hi = -Infinity;
|
|
554
|
+
for (const bar of b) {
|
|
555
|
+
if (bar.low < lo) lo = bar.low;
|
|
556
|
+
if (bar.high > hi) hi = bar.high;
|
|
557
|
+
}
|
|
558
|
+
if (!(hi >= lo)) return true;
|
|
559
|
+
const margin = (hi - lo) * 0.25;
|
|
560
|
+
let inside = 0;
|
|
561
|
+
let total = 0;
|
|
562
|
+
// the plots shown on the chart only (display 'none': values for alerts or other scripts)
|
|
563
|
+
const shown = c.plotConfig.filter((p) => p.display !== 'none').map((p) => c.plots[p.id] ?? []);
|
|
564
|
+
for (const points of shown) {
|
|
565
|
+
for (const p of points) {
|
|
566
|
+
total++;
|
|
567
|
+
if (p.value >= lo - margin && p.value <= hi + margin) inside++;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
return total === 0 || inside >= total * 0.9;
|
|
571
|
+
}
|
|
572
|
+
|
|
361
573
|
// ── Host entry ───────────────────────────────────────────────────────────────
|
|
362
574
|
|
|
363
575
|
/** What the host passes to its strategy engine factory when the script declares strategy(). */
|
|
@@ -375,6 +587,35 @@ export interface ScriptOptions {
|
|
|
375
587
|
* (see {@link executeIntrabar}). The host keeps one recorder for the main run of a backtest and its intrabar runs.
|
|
376
588
|
*/
|
|
377
589
|
recorder?: StrategyRecorder;
|
|
590
|
+
/**
|
|
591
|
+
* Strict mode: mistakes that PineScript lets pass silently throw a {@link ScriptError} with a plain message: an input
|
|
592
|
+
* value of the wrong type, out of its range or not one of its options, an input name the script does not declare,
|
|
593
|
+
* an unknown option of plot() / hline() / plotshape() / plotchar() / bgcolor() / barcolor(), a text that is not a
|
|
594
|
+
* colour. Default false (PineScript behaviour); {@link defineIndicator} turns it on.
|
|
595
|
+
*/
|
|
596
|
+
strict?: boolean;
|
|
597
|
+
/**
|
|
598
|
+
* Colours of the plots that give none: true for {@link DEFAULT_PALETTE} (each plot without a colour takes the next
|
|
599
|
+
* one), or a list of colours. Default false: every plot without a colour is blue, as in PineScript.
|
|
600
|
+
*/
|
|
601
|
+
palette?: boolean | readonly string[];
|
|
602
|
+
/**
|
|
603
|
+
* The ids of the plots in `plotConfig` and `result.plots`: 'index' (default, as PineScript numbers them: plot0,
|
|
604
|
+
* plot1...) or 'title' (made from the title as the inputs' ids are: "Fast MA" gives fast_ma), which stay the same when
|
|
605
|
+
* plots are added or moved.
|
|
606
|
+
*/
|
|
607
|
+
plotIds?: 'index' | 'title';
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/** The colours given in turn to plots without a colour when `ScriptOptions.palette` is true. */
|
|
611
|
+
export const DEFAULT_PALETTE: readonly string[] = ['#2962FF', '#FF6D00', '#00897B', '#AB47BC', '#F23645', '#43A047', '#FBC02D', '#8D6E63'];
|
|
612
|
+
|
|
613
|
+
/** A mistake found in strict mode (see `ScriptOptions.strict`): the message says what to change. */
|
|
614
|
+
export class ScriptError extends Error {
|
|
615
|
+
constructor(message: string) {
|
|
616
|
+
super(message);
|
|
617
|
+
this.name = 'ScriptError';
|
|
618
|
+
}
|
|
378
619
|
}
|
|
379
620
|
|
|
380
621
|
let scriptOptions: ScriptOptions = {};
|
|
@@ -498,7 +739,7 @@ function runBody(
|
|
|
498
739
|
chartCtx = { ...chart };
|
|
499
740
|
runNow = chart.now ?? Date.now();
|
|
500
741
|
scriptOptions = options;
|
|
501
|
-
ctx = freshCollector(inputs);
|
|
742
|
+
ctx = freshCollector(inputs, options.strict === true);
|
|
502
743
|
intrabarRun = null;
|
|
503
744
|
varipRun = { slot: 0, recorder: options.recorder ?? null, mode: 'live', scratch: null };
|
|
504
745
|
currentBar = -1;
|
|
@@ -515,6 +756,8 @@ function runBody(
|
|
|
515
756
|
throw err;
|
|
516
757
|
}
|
|
517
758
|
if (missingSymbols.length) throw new MissingSymbolDataError(missingSymbols);
|
|
759
|
+
if (ctx.strict) checkInputNames(ctx, inputs);
|
|
760
|
+
if (ctx.paneAuto) ctx.overlay = plotsOnPrices(ctx);
|
|
518
761
|
// the outputs read the drawings: not a drawing of the script
|
|
519
762
|
if (inc) incremental.bodyDone();
|
|
520
763
|
const c = ctx;
|
|
@@ -526,6 +769,7 @@ function runBody(
|
|
|
526
769
|
precision: c.precision,
|
|
527
770
|
format: c.format,
|
|
528
771
|
...(c.scale ? { scale: c.scale } : {}),
|
|
772
|
+
...(c.pane ? { pane: c.pane } : {}),
|
|
529
773
|
},
|
|
530
774
|
inputConfig: c.inputConfig,
|
|
531
775
|
plotConfig: c.plotConfig,
|
|
@@ -559,6 +803,7 @@ function runBody(
|
|
|
559
803
|
},
|
|
560
804
|
hasAlertFunction: c.hasAlertFunction,
|
|
561
805
|
usesVisibleRange: c.usesVisibleRange,
|
|
806
|
+
warnings: runWarnings(),
|
|
562
807
|
};
|
|
563
808
|
} finally {
|
|
564
809
|
ctx = null;
|
|
@@ -655,23 +900,28 @@ function setVarip(recorder: StrategyRecorder, values: unknown[]): void {
|
|
|
655
900
|
}
|
|
656
901
|
|
|
657
902
|
/**
|
|
658
|
-
*
|
|
659
|
-
*
|
|
660
|
-
* the tick price, its high and low the extremes reached so far). The script's variables come back to
|
|
661
|
-
* the start of the bar
|
|
662
|
-
*
|
|
663
|
-
*
|
|
664
|
-
*
|
|
665
|
-
*
|
|
666
|
-
*
|
|
903
|
+
* Host-side: runs a strategy once more on one bar, inside the bar (calculation on order fills, or on the ticks of
|
|
904
|
+
* history bars). Scripts never call it. `bars` holds the bars up to that bar, the last one as it stands at the tick
|
|
905
|
+
* (its close is the tick price, its high and low the extremes reached so far). The script's variables come back to
|
|
906
|
+
* their state at the start of the bar, except `varip` ones. In strategy.eachBar(), the bars before replay the engine's
|
|
907
|
+
* answers that the main run recorded (their order calls are dropped), and the bar itself calls `options.engine`
|
|
908
|
+
* without processBar / processClose (the host is filling its orders). That bar is a confirmed history bar
|
|
909
|
+
* (`barstate.isconfirmed`); `barstate.islast`, `last_bar_index` and `BarContext.n` keep the chart's last bar. Risk
|
|
910
|
+
* rules are not declared again, and the outputs (plots, drawings) are dropped. Re-entrant: the host calls it inside
|
|
911
|
+
* the bar loop of the main run.
|
|
667
912
|
*
|
|
668
|
-
* Resumed runs
|
|
669
|
-
*
|
|
670
|
-
*
|
|
671
|
-
*
|
|
672
|
-
*
|
|
673
|
-
*
|
|
674
|
-
*
|
|
913
|
+
* Resumed runs: the intrabar runs of a backtest (same recorder, script, inputs, chart and engine) keep the state of
|
|
914
|
+
* the script as createScriptRun does, so a run calculates its bar only (and the bars since the previous intrabar run);
|
|
915
|
+
* the order calls and `strategy.*` reads are the same as in a full run. The bars before `options.bar` must be the main
|
|
916
|
+
* run's (the same on every call). A script that keeps state outside `persist()` boxes, or uses a feature that is not
|
|
917
|
+
* resumed, gets full runs (`fullRunReason`); the first resumed runs are also calculated in full and compared
|
|
918
|
+
* (`verify`). A resumed run gives its order calls to the engine once it has ended.
|
|
919
|
+
* @param body - The script body, as given to executeScript().
|
|
920
|
+
* @param bars - The bars up to and including the bar calculated inside, oldest first.
|
|
921
|
+
* @param inputs - Input values by input id, as given to the main run.
|
|
922
|
+
* @param chart - The chart context of the main run.
|
|
923
|
+
* @param options - The bar, the chart's last bar index, the main run's engine and recorder, and the resume settings.
|
|
924
|
+
* @returns The first bar calculated, whether the run was resumed, and why the runs are full ones (or null).
|
|
675
925
|
*/
|
|
676
926
|
export function executeIntrabar(
|
|
677
927
|
body: () => void,
|
|
@@ -910,7 +1160,8 @@ function sameResult(a: unknown, b: unknown): boolean {
|
|
|
910
1160
|
}
|
|
911
1161
|
|
|
912
1162
|
/**
|
|
913
|
-
*
|
|
1163
|
+
* Host-side: a script that calculates only the newest bars on a live update. Scripts never call it. The first
|
|
1164
|
+
* update is a full run; it keeps,
|
|
914
1165
|
* for the next one, what the script created (its Series, ta.* calls, eachBar() blocks, persist() boxes and plots) with
|
|
915
1166
|
* their state at the end of the last confirmed bar. An update whose bars are the same up to the forming bar of the
|
|
916
1167
|
* previous update (a new price of the forming bar, or new bars after it) runs the script again from that bar only;
|
|
@@ -922,6 +1173,13 @@ function sameResult(a: unknown, b: unknown): boolean {
|
|
|
922
1173
|
* compared (`verify`): a difference makes the next updates full runs. Not resumed yet, so calculated in full: drawings,
|
|
923
1174
|
* request.security, strategies, varip, timenow, last_bar_index, BarContext.n, barstate.islastconfirmedhistory
|
|
924
1175
|
* (`fullRunReason` names the first one met).
|
|
1176
|
+
* @param body - The script body, a function that runs the script's statements.
|
|
1177
|
+
* @param inputs - Input values by input id. Default: `{}` (every input at its default).
|
|
1178
|
+
* @param chart - The chart context (timeframe, time zone, session, symbol...); an update can give a new one.
|
|
1179
|
+
* Default: `{}`.
|
|
1180
|
+
* @param options - The executeScript() options, plus `verify` (resumed updates also run in full and compared).
|
|
1181
|
+
* Default: `{}`.
|
|
1182
|
+
* @returns A run: call `update(bars, chart?)` on each change of the bars; `fullRunReason` says why it does not resume.
|
|
925
1183
|
*/
|
|
926
1184
|
export function createScriptRun(
|
|
927
1185
|
body: () => void,
|
|
@@ -1021,14 +1279,24 @@ let varipRun: VaripRun = { slot: 0, recorder: null, mode: 'live', scratch: null
|
|
|
1021
1279
|
|
|
1022
1280
|
/** A `varip` variable: `.value` reads and writes it. */
|
|
1023
1281
|
export interface VaripVariable<T> {
|
|
1282
|
+
/** The current value of the variable. */
|
|
1024
1283
|
value: T;
|
|
1025
1284
|
}
|
|
1026
1285
|
|
|
1027
1286
|
/**
|
|
1028
|
-
*
|
|
1029
|
-
*
|
|
1030
|
-
*
|
|
1031
|
-
*
|
|
1287
|
+
* A strategy variable that keeps the changes made while a bar is calculated again inside the bar (on order fills or
|
|
1288
|
+
* ticks). A plain variable comes back to its value at the start of the bar on each of those runs; a `varip` one does
|
|
1289
|
+
* not, so it can count fills or ticks. Declare it once in the script body (outside the callbacks), in the same order
|
|
1290
|
+
* on each run; read and write `.value` in strategy.eachBar(). Without intrabar runs it is a plain variable.
|
|
1291
|
+
* @param initial - The starting value.
|
|
1292
|
+
* @returns A box whose `.value` reads and writes the variable.
|
|
1293
|
+
* @example
|
|
1294
|
+
* ```js
|
|
1295
|
+
* const updatesInTrade = varip(0);
|
|
1296
|
+
* strategy.eachBar((c) => {
|
|
1297
|
+
* if (strategy.position_size !== 0) updatesInTrade.value += 1;
|
|
1298
|
+
* });
|
|
1299
|
+
* ```
|
|
1032
1300
|
*/
|
|
1033
1301
|
export function varip<T>(initial: T): VaripVariable<T> {
|
|
1034
1302
|
collector();
|
|
@@ -1068,22 +1336,23 @@ export function varip<T>(initial: T): VaripVariable<T> {
|
|
|
1068
1336
|
|
|
1069
1337
|
/** A `persist` variable: `.value` reads and writes it. */
|
|
1070
1338
|
export interface PersistVariable<T> {
|
|
1339
|
+
/** The current value of the variable. */
|
|
1071
1340
|
value: T;
|
|
1072
1341
|
}
|
|
1073
1342
|
|
|
1074
1343
|
/**
|
|
1075
|
-
*
|
|
1076
|
-
*
|
|
1077
|
-
*
|
|
1078
|
-
*
|
|
1079
|
-
*
|
|
1080
|
-
*
|
|
1081
|
-
*
|
|
1082
|
-
*
|
|
1083
|
-
*
|
|
1084
|
-
*
|
|
1085
|
-
* ```
|
|
1086
|
-
* const dir = persist(0);
|
|
1344
|
+
* A variable that keeps its value from one bar to the next, kept by the runtime. Declare it in the script body
|
|
1345
|
+
* (outside the callbacks), in the same order on each run, and read and write `.value` in one eachBar() callback. On a
|
|
1346
|
+
* live chart the runtime saves its value at the end of the last confirmed bar and puts it back before the forming bar
|
|
1347
|
+
* is calculated again, so only the newest bar is calculated: prefer it to a `let` variable outside the callback.
|
|
1348
|
+
* The script is calculated in full on each update (same results, slower) when the variable is used outside an
|
|
1349
|
+
* eachBar() callback, by two eachBar() blocks, or holds something else than plain data (numbers, strings, booleans,
|
|
1350
|
+
* arrays, plain objects, Map, Set). Calling it inside a bar loop throws.
|
|
1351
|
+
* @param initial - The value before the first bar.
|
|
1352
|
+
* @returns A box whose `.value` reads and writes the variable.
|
|
1353
|
+
* @example
|
|
1354
|
+
* ```js
|
|
1355
|
+
* const dir = persist(0);
|
|
1087
1356
|
* const trend = eachBar((c) => {
|
|
1088
1357
|
* if (c.close > c.get(close, 1)) dir.value = 1;
|
|
1089
1358
|
* else if (c.close < c.get(close, 1)) dir.value = -1;
|
|
@@ -1140,31 +1409,60 @@ export function persist<T>(initial: T): PersistVariable<T> {
|
|
|
1140
1409
|
|
|
1141
1410
|
// ── Declarations ─────────────────────────────────────────────────────────────
|
|
1142
1411
|
|
|
1412
|
+
/** Options of {@link indicator}. */
|
|
1143
1413
|
export interface IndicatorOptions {
|
|
1414
|
+
/** Short name shown in the chart legend. Default: the title. */
|
|
1144
1415
|
shorttitle?: string;
|
|
1145
|
-
/** true: drawn on the price pane; false
|
|
1416
|
+
/** true: drawn on the price pane; false: in its own pane below the chart. Default: false. */
|
|
1146
1417
|
overlay?: boolean;
|
|
1418
|
+
/** Number of decimals of the values shown in the legend and on the price scale. Default: the host's choice (the symbol's precision). */
|
|
1147
1419
|
precision?: number;
|
|
1420
|
+
/** Number format of the values: `format.price`, `format.volume`, `format.percent`, `format.mintick` or `format.inherit`. Default: `format.inherit`. */
|
|
1148
1421
|
format?: string;
|
|
1149
|
-
/** The price scale: `scale.right`, `scale.left` or `scale.none
|
|
1422
|
+
/** The price scale the script uses: `scale.right`, `scale.left` or `scale.none`. Default: the host's choice. */
|
|
1150
1423
|
scale?: 'right' | 'left' | 'none';
|
|
1151
|
-
/**
|
|
1424
|
+
/** Most lines kept alive; above it the oldest are deleted (a few more may stay for a moment). Default: 50. */
|
|
1152
1425
|
max_lines_count?: number;
|
|
1153
|
-
/**
|
|
1426
|
+
/** Most labels kept alive; above it the oldest are deleted. Default: 50. */
|
|
1154
1427
|
max_labels_count?: number;
|
|
1155
|
-
/**
|
|
1428
|
+
/** Most boxes kept alive; above it the oldest are deleted. Default: 50. */
|
|
1156
1429
|
max_boxes_count?: number;
|
|
1157
|
-
/**
|
|
1430
|
+
/** Most polylines kept alive; above it the oldest are deleted. Default: 50. */
|
|
1158
1431
|
max_polylines_count?: number;
|
|
1432
|
+
/**
|
|
1433
|
+
* Where the script is drawn, instead of `overlay` (give one of the two): 'price' (on the price pane), 'separate'
|
|
1434
|
+
* (its own pane) or 'auto' (chosen from the plotted values: the price pane when they are prices, like an average;
|
|
1435
|
+
* its own pane otherwise, like an RSI). Default: not set (`overlay` decides).
|
|
1436
|
+
*/
|
|
1437
|
+
pane?: 'price' | 'separate' | 'auto';
|
|
1159
1438
|
}
|
|
1160
1439
|
|
|
1161
|
-
/**
|
|
1440
|
+
/**
|
|
1441
|
+
* Declares the script as an indicator: its title, its pane and how its values are shown. Call it once, at the top
|
|
1442
|
+
* of the script (a script declares either `indicator()` or `strategy()`). A script without a declaration runs with
|
|
1443
|
+
* the title "Untitled" in its own pane.
|
|
1444
|
+
* @param title - Name of the script, shown in the legend and the settings.
|
|
1445
|
+
* @param options - Pane, short title, number format and drawing limits. Default: `{}` (own pane).
|
|
1446
|
+
* @example
|
|
1447
|
+
* ```js
|
|
1448
|
+
* indicator("My SMA", { overlay: true, precision: 2 });
|
|
1449
|
+
* plot(ta.sma(close, 20), "SMA");
|
|
1450
|
+
* ```
|
|
1451
|
+
*/
|
|
1162
1452
|
export function indicator(title: string, options: IndicatorOptions = {}): void {
|
|
1163
1453
|
const c = collector();
|
|
1164
1454
|
declare(c, 'indicator');
|
|
1165
1455
|
c.title = title;
|
|
1166
1456
|
c.shortTitle = options.shorttitle;
|
|
1167
|
-
|
|
1457
|
+
if (options.pane !== undefined) {
|
|
1458
|
+
if (!['price', 'separate', 'auto'].includes(options.pane)) {
|
|
1459
|
+
throw new ScriptError(`indicator(): pane is 'price', 'separate' or 'auto', got ${shown(options.pane)}.`);
|
|
1460
|
+
}
|
|
1461
|
+
if (options.overlay !== undefined) throw new ScriptError('indicator(): give overlay or pane, not both.');
|
|
1462
|
+
}
|
|
1463
|
+
c.overlay = options.pane === 'price' ? true : options.pane === undefined ? (options.overlay ?? false) : false;
|
|
1464
|
+
c.paneAuto = options.pane === 'auto';
|
|
1465
|
+
c.pane = options.pane;
|
|
1168
1466
|
c.precision = options.precision;
|
|
1169
1467
|
c.format = options.format;
|
|
1170
1468
|
c.scale = options.scale;
|
|
@@ -1183,44 +1481,59 @@ function declare(c: Collector, kind: 'indicator' | 'strategy'): void {
|
|
|
1183
1481
|
c.declaration = kind;
|
|
1184
1482
|
}
|
|
1185
1483
|
|
|
1186
|
-
/** Options of every `input.*` kind
|
|
1484
|
+
/** Options of every `input.*` kind: where the input is listed in the settings and how it behaves. */
|
|
1187
1485
|
export interface InputOptions {
|
|
1188
|
-
/** Group title: every input with the same `group` is listed under it, at the place of the group's first input. */
|
|
1486
|
+
/** Group title: every input with the same `group` is listed under it, at the place of the group's first input. Default: no group. */
|
|
1189
1487
|
group?: string;
|
|
1190
|
-
/** Inputs with the same `inline` id share one row of their group (ungrouped inputs share rows among themselves). */
|
|
1488
|
+
/** Inputs with the same `inline` id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own. */
|
|
1191
1489
|
inline?: string;
|
|
1192
|
-
/** Help text shown next to the input. */
|
|
1490
|
+
/** Help text shown next to the input. Default: none. */
|
|
1193
1491
|
tooltip?: string;
|
|
1194
|
-
/**
|
|
1492
|
+
/** true: the host asks for the value when the script is added to a chart. Default: false. */
|
|
1195
1493
|
confirm?: boolean;
|
|
1196
|
-
/**
|
|
1494
|
+
/**
|
|
1495
|
+
* Where the value is shown besides the settings: `display.all`, `display.none`, `display.status_line` or
|
|
1496
|
+
* `display.data_window`. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.
|
|
1497
|
+
*/
|
|
1197
1498
|
display?: InputConfig['display'];
|
|
1198
1499
|
/**
|
|
1199
|
-
*
|
|
1200
|
-
*
|
|
1201
|
-
*
|
|
1500
|
+
* false greys the input out in the settings (it keeps its value). A boolean (`active: showMa`), or a condition on
|
|
1501
|
+
* input ids that a host can apply without running the script (`active: 'ma_1'`,
|
|
1502
|
+
* `active: { input: 'type', ne: 'None' }`). Default: true.
|
|
1202
1503
|
*/
|
|
1203
1504
|
active?: boolean | InputCondition;
|
|
1505
|
+
/**
|
|
1506
|
+
* The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made
|
|
1507
|
+
* from the title ("Fast length" gives fast_length), which changes when the title changes.
|
|
1508
|
+
*/
|
|
1509
|
+
id?: string;
|
|
1204
1510
|
}
|
|
1205
1511
|
|
|
1512
|
+
/** Options of `input.int()` and `input.float()`. */
|
|
1206
1513
|
export interface NumericInputOptions extends InputOptions {
|
|
1514
|
+
/** Smallest value the user can enter. Default: no minimum. */
|
|
1207
1515
|
minval?: number;
|
|
1516
|
+
/** Largest value the user can enter. Default: no maximum. */
|
|
1208
1517
|
maxval?: number;
|
|
1518
|
+
/** Step of the arrows of the number field. Default: the host's choice (1 for an int). */
|
|
1209
1519
|
step?: number;
|
|
1210
|
-
/** The values to choose from (the host shows a drop-down list). */
|
|
1520
|
+
/** The values to choose from (the host shows a drop-down list). Default: a free number field. */
|
|
1211
1521
|
options?: number[];
|
|
1212
1522
|
}
|
|
1213
1523
|
|
|
1214
|
-
/** A field of an enum made with `defineEnum()`: its name and title. `String(field)` is the title
|
|
1215
|
-
* `str.tostring()` of an enum field. */
|
|
1524
|
+
/** A field of an enum made with `defineEnum()`: its name and title. `String(field)` is the title. */
|
|
1216
1525
|
export interface EnumField {
|
|
1526
|
+
/** The field's name, as written in `defineEnum()` (`"sma"`). */
|
|
1217
1527
|
readonly name: string;
|
|
1528
|
+
/** The field's title, shown in the settings (`"Simple"`); the name when the title was empty. */
|
|
1218
1529
|
readonly title: string;
|
|
1530
|
+
/** The title, so `String(field)` and `str.tostring(field)` give it. */
|
|
1219
1531
|
toString(): string;
|
|
1220
1532
|
}
|
|
1221
1533
|
|
|
1534
|
+
/** Options of `input.enum()`. */
|
|
1222
1535
|
export interface EnumInputOptions extends InputOptions {
|
|
1223
|
-
/** The fields to choose from
|
|
1536
|
+
/** The fields to choose from, all of the default's enum. Default: every field of the enum. */
|
|
1224
1537
|
options?: EnumField[];
|
|
1225
1538
|
}
|
|
1226
1539
|
|
|
@@ -1238,9 +1551,17 @@ class EnumFieldValue implements EnumField {
|
|
|
1238
1551
|
const enumFieldsOf = new WeakMap<EnumField, readonly EnumField[]>();
|
|
1239
1552
|
|
|
1240
1553
|
/**
|
|
1241
|
-
*
|
|
1242
|
-
*
|
|
1243
|
-
*
|
|
1554
|
+
* Makes an enum: a fixed set of named fields, each with a title, for a choice list (`input.enum()`) or a state with
|
|
1555
|
+
* a few values. Fields compare with `===`; `field.name` is the name, `field.title` and `String(field)` the title.
|
|
1556
|
+
* @param fields - An object of field names and titles, e.g. `{ sma: "Simple", ema: "Exponential" }`; an empty title
|
|
1557
|
+
* is the name.
|
|
1558
|
+
* @returns A frozen object with one {@link EnumField} per name.
|
|
1559
|
+
* @example
|
|
1560
|
+
* ```js
|
|
1561
|
+
* const MaType = defineEnum({ sma: "Simple", ema: "Exponential" });
|
|
1562
|
+
* const maType = input.enum(MaType.sma, "Average");
|
|
1563
|
+
* plot(maType === MaType.ema ? ta.ema(close, 20) : ta.sma(close, 20), "MA");
|
|
1564
|
+
* ```
|
|
1244
1565
|
*/
|
|
1245
1566
|
export function defineEnum<K extends string>(fields: Record<K, string>): { readonly [P in K]: EnumField } {
|
|
1246
1567
|
if (!isPlainObject(fields) || Object.keys(fields).length === 0) {
|
|
@@ -1258,7 +1579,9 @@ export function defineEnum<K extends string>(fields: Record<K, string>): { reado
|
|
|
1258
1579
|
return Object.freeze(out) as { readonly [P in K]: EnumField };
|
|
1259
1580
|
}
|
|
1260
1581
|
|
|
1582
|
+
/** Options of `input.string()`, `input.timeframe()`, `input.session()` and `input.symbol()`. */
|
|
1261
1583
|
export interface StringInputOptions extends InputOptions {
|
|
1584
|
+
/** The values to choose from (the host shows a drop-down list). Default: a free text field (or the kind's own picker). */
|
|
1262
1585
|
options?: string[];
|
|
1263
1586
|
}
|
|
1264
1587
|
|
|
@@ -1271,6 +1594,7 @@ function common(opts: InputOptions): Partial<InputConfig> {
|
|
|
1271
1594
|
if (opts.confirm !== undefined) out.confirm = opts.confirm;
|
|
1272
1595
|
if (opts.display !== undefined) out.display = opts.display;
|
|
1273
1596
|
if (opts.active !== undefined) out.active = opts.active;
|
|
1597
|
+
if (opts.id !== undefined) out.id = opts.id;
|
|
1274
1598
|
return out;
|
|
1275
1599
|
}
|
|
1276
1600
|
|
|
@@ -1278,10 +1602,22 @@ function common(opts: InputOptions): Partial<InputConfig> {
|
|
|
1278
1602
|
* host-supplied override when present, else the default). */
|
|
1279
1603
|
function registerInput<T>(config: Omit<InputConfig, 'id'>, fallbackId: string): T {
|
|
1280
1604
|
const c = collector();
|
|
1281
|
-
const
|
|
1282
|
-
|
|
1605
|
+
const wanted = (config as Partial<InputConfig>).id;
|
|
1606
|
+
let id: string;
|
|
1607
|
+
if (wanted !== undefined) {
|
|
1608
|
+
if (typeof wanted !== 'string' || !/^[A-Za-z_]\w*$/.test(wanted)) {
|
|
1609
|
+
throw new ScriptError(`input id ${shown(wanted)}: letters, digits and _ only, not starting with a digit, e.g. "fast_length".`);
|
|
1610
|
+
}
|
|
1611
|
+
if (c.inputIds.has(wanted)) throw new ScriptError(`Two inputs have the id "${wanted}": give each its own.`);
|
|
1612
|
+
c.inputIds.add(wanted);
|
|
1613
|
+
id = wanted;
|
|
1614
|
+
} else {
|
|
1615
|
+
id = slugId(config.title, fallbackId, c.inputIds);
|
|
1616
|
+
}
|
|
1617
|
+
c.inputConfig.push({ ...config, id });
|
|
1283
1618
|
c.defaultInputs[id] = config.defval;
|
|
1284
1619
|
const value = c.inputValues[id];
|
|
1620
|
+
if (c.strict && value !== undefined) checkInputValue({ id, ...config }, id, value);
|
|
1285
1621
|
return (value === undefined ? config.defval : value) as T;
|
|
1286
1622
|
}
|
|
1287
1623
|
|
|
@@ -1297,7 +1633,7 @@ function registerNumeric(type: 'int' | 'float' | 'price', defval: number, title?
|
|
|
1297
1633
|
/** Named arguments of an input: its options, with `title` (and `defval` when every argument is named). */
|
|
1298
1634
|
type InputArgs<O, D> = O & { title?: string; defval?: D };
|
|
1299
1635
|
|
|
1300
|
-
const COMMON_INPUT_KEYS = ['tooltip', 'inline', 'group', 'confirm', 'display', 'active'] as const;
|
|
1636
|
+
const COMMON_INPUT_KEYS = ['tooltip', 'inline', 'group', 'confirm', 'display', 'active', 'id'] as const;
|
|
1301
1637
|
/** The PineScript arguments of each input kind (named arguments are checked against them). */
|
|
1302
1638
|
const INPUT_KEYS: Record<string, readonly string[]> = {
|
|
1303
1639
|
int: ['defval', 'title', 'minval', 'maxval', 'step', 'options', ...COMMON_INPUT_KEYS],
|
|
@@ -1355,71 +1691,215 @@ function inputArgs<D, O extends object>(
|
|
|
1355
1691
|
};
|
|
1356
1692
|
}
|
|
1357
1693
|
|
|
1358
|
-
/**
|
|
1359
|
-
*
|
|
1360
|
-
*
|
|
1694
|
+
/**
|
|
1695
|
+
* Script inputs: each `input.*` call declares a setting the user can change AND returns its current value (the
|
|
1696
|
+
* user's value when there is one, else the default). The arguments after the default can be named:
|
|
1697
|
+
* `input.int(14, "Length", { minval: 1 })`, `input.int(14, { title: "Length", minval: 1 })` or
|
|
1698
|
+
* `input.int({ defval: 14, title: "Length" })`. The input id is the title in snake case ("Fast length" is
|
|
1699
|
+
* `fast_length`); keep titles stable, a renamed input loses the user's value.
|
|
1700
|
+
*/
|
|
1361
1701
|
export const input = strictNamespace('input', {
|
|
1702
|
+
/**
|
|
1703
|
+
* Declares a whole-number setting (a length, a count) and returns its value, rounded to an integer.
|
|
1704
|
+
* @param defval - Default value, or every argument by name (`{ defval, title, minval... }`).
|
|
1705
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_int`).
|
|
1706
|
+
* @param opts - `minval`, `maxval`, `step`, `options` (a choice list) and the common input options.
|
|
1707
|
+
* @returns The current value: the user's value, else `defval`.
|
|
1708
|
+
* @example
|
|
1709
|
+
* ```js
|
|
1710
|
+
* const length = input.int(14, "Length", { minval: 1, maxval: 500 });
|
|
1711
|
+
* plot(ta.rsi(close, length), "RSI");
|
|
1712
|
+
* ```
|
|
1713
|
+
*/
|
|
1362
1714
|
int(defval: number | InputArgs<NumericInputOptions, number>, title?: string | InputArgs<NumericInputOptions, number>, opts?: NumericInputOptions): number {
|
|
1363
1715
|
const a = inputArgs<number, NumericInputOptions>('int', defval, title, opts);
|
|
1364
1716
|
return Math.round(registerNumeric('int', a.defval, a.title, a.opts));
|
|
1365
1717
|
},
|
|
1718
|
+
/**
|
|
1719
|
+
* Declares a decimal-number setting (a multiplier, a percent, a level) and returns its value.
|
|
1720
|
+
* @param defval - Default value, or every argument by name (`{ defval, title, minval... }`).
|
|
1721
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_float`).
|
|
1722
|
+
* @param opts - `minval`, `maxval`, `step`, `options` (a choice list) and the common input options.
|
|
1723
|
+
* @returns The current value: the user's value, else `defval`.
|
|
1724
|
+
* @example
|
|
1725
|
+
* ```js
|
|
1726
|
+
* const mult = input.float(2.0, "Multiplier", { minval: 0.1, step: 0.1 });
|
|
1727
|
+
* const [basis, upper, lower] = ta.bb(close, 20, mult);
|
|
1728
|
+
* ```
|
|
1729
|
+
*/
|
|
1366
1730
|
float(defval: number | InputArgs<NumericInputOptions, number>, title?: string | InputArgs<NumericInputOptions, number>, opts?: NumericInputOptions): number {
|
|
1367
1731
|
const a = inputArgs<number, NumericInputOptions>('float', defval, title, opts);
|
|
1368
1732
|
return registerNumeric('float', a.defval, a.title, a.opts);
|
|
1369
1733
|
},
|
|
1734
|
+
/**
|
|
1735
|
+
* Declares an on / off setting (a checkbox) and returns its value. Shown only in the settings by default.
|
|
1736
|
+
* @param defval - Default value, or every argument by name (`{ defval, title... }`).
|
|
1737
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_bool`).
|
|
1738
|
+
* @param opts - The common input options (`group`, `inline`, `tooltip`, `confirm`, `display`, `active`, `id`).
|
|
1739
|
+
* @returns The current value: the user's value, else `defval`.
|
|
1740
|
+
* @example
|
|
1741
|
+
* ```js
|
|
1742
|
+
* const showMa = input.bool(true, "Show MA");
|
|
1743
|
+
* plot(ta.sma(close, 20), "MA", { display: showMa ? display.all : display.none });
|
|
1744
|
+
* ```
|
|
1745
|
+
*/
|
|
1370
1746
|
bool(defval: boolean | InputArgs<InputOptions, boolean>, title?: string | InputArgs<InputOptions, boolean>, opts?: InputOptions): boolean {
|
|
1371
1747
|
const a = inputArgs<boolean, InputOptions>('bool', defval, title, opts);
|
|
1372
1748
|
return registerInput<boolean>({ type: 'bool', defval: a.defval, title: a.title, ...common(a.opts) }, 'input_bool');
|
|
1373
1749
|
},
|
|
1750
|
+
/**
|
|
1751
|
+
* Declares a text setting and returns its value; with `options`, a drop-down list of choices.
|
|
1752
|
+
* @param defval - Default value (one of `options` when they are given), or every argument by name.
|
|
1753
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_string`).
|
|
1754
|
+
* @param opts - `options` (a choice list) and the common input options.
|
|
1755
|
+
* @returns The current value: the user's value, else `defval`.
|
|
1756
|
+
* @example
|
|
1757
|
+
* ```js
|
|
1758
|
+
* const maType = input.string("EMA", "MA type", { options: ["SMA", "EMA"] });
|
|
1759
|
+
* const ma = maType === "SMA" ? ta.sma(close, 20) : ta.ema(close, 20);
|
|
1760
|
+
* ```
|
|
1761
|
+
*/
|
|
1374
1762
|
string(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string {
|
|
1375
1763
|
const a = inputArgs<string, StringInputOptions>('string', defval, title, opts);
|
|
1376
1764
|
return registerInput<string>({ type: 'string', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_string');
|
|
1377
1765
|
},
|
|
1378
|
-
/**
|
|
1766
|
+
/**
|
|
1767
|
+
* Declares a multi-line text setting (lines separated by a newline) and returns its value, e.g. a list of levels
|
|
1768
|
+
* the script parses. Shown only in the settings by default.
|
|
1769
|
+
* @param defval - Default text, or every argument by name.
|
|
1770
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_text_area`).
|
|
1771
|
+
* @param opts - The common input options.
|
|
1772
|
+
* @returns The current text: the user's text, else `defval`.
|
|
1773
|
+
* @example
|
|
1774
|
+
* ```js
|
|
1775
|
+
* const text = input.text_area("100\n105\n110", "Levels");
|
|
1776
|
+
* for (const lvl of text.split("\n")) hline(Number(lvl), "Level " + lvl);
|
|
1777
|
+
* ```
|
|
1778
|
+
*/
|
|
1379
1779
|
text_area(defval: string | InputArgs<InputOptions, string>, title?: string | InputArgs<InputOptions, string>, opts?: InputOptions): string {
|
|
1380
1780
|
const a = inputArgs<string, InputOptions>('text_area', defval, title, opts);
|
|
1381
1781
|
return registerInput<string>({ type: 'text_area', defval: a.defval, title: a.title, ...common(a.opts) }, 'input_text_area');
|
|
1382
1782
|
},
|
|
1383
1783
|
/**
|
|
1384
|
-
* Declares a colour
|
|
1385
|
-
* `color.new(c, 90)`
|
|
1784
|
+
* Declares a colour setting (a colour picker) and returns its value. The default's transparency is kept to 2
|
|
1785
|
+
* decimals (`color.new(c, 90)` gives the alpha byte 26); a value given by the host is used as it is. Shown only in
|
|
1786
|
+
* the settings by default.
|
|
1787
|
+
* @param defval - Default colour (`color.blue`, `"#2962FF"`, `color.new(...)`), or every argument by name.
|
|
1788
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_color`).
|
|
1789
|
+
* @param opts - The common input options.
|
|
1790
|
+
* @returns The current colour string: the user's colour, else `defval`.
|
|
1791
|
+
* @example
|
|
1792
|
+
* ```js
|
|
1793
|
+
* const lineColor = input.color(color.teal, "Line colour");
|
|
1794
|
+
* plot(ta.ema(close, 20), "EMA", { color: lineColor });
|
|
1795
|
+
* ```
|
|
1386
1796
|
*/
|
|
1387
1797
|
color(defval: string | InputArgs<InputOptions, string>, title?: string | InputArgs<InputOptions, string>, opts?: InputOptions): string {
|
|
1388
1798
|
const a = inputArgs<string, InputOptions>('color', defval, title, opts);
|
|
1389
1799
|
return registerInput<string>({ type: 'color', defval: inputColorDefault(a.defval), title: a.title, ...common(a.opts) }, 'input_color');
|
|
1390
1800
|
},
|
|
1391
|
-
/**
|
|
1801
|
+
/**
|
|
1802
|
+
* Declares a source setting (the price a calculation reads) and returns it as a Series. The choices are `open`,
|
|
1803
|
+
* `high`, `low`, `close`, `volume`, `hl2`, `hlc3`, `ohlc4`, `hlcc4`, and the outputs of other scripts on the chart
|
|
1804
|
+
* when the host allows it (an unknown source gives `close`).
|
|
1805
|
+
* @param defval - Default source, by name (`"close"`) or as the built-in Series (`close`), or every argument by
|
|
1806
|
+
* name. Default: `"close"`.
|
|
1807
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_source`).
|
|
1808
|
+
* @param opts - The common input options.
|
|
1809
|
+
* @returns The chosen source as a Series.
|
|
1810
|
+
* @example
|
|
1811
|
+
* ```js
|
|
1812
|
+
* const src = input.source(close, "Source");
|
|
1813
|
+
* plot(ta.sma(src, 20), "SMA");
|
|
1814
|
+
* ```
|
|
1815
|
+
*/
|
|
1392
1816
|
source(defval: string | Series = 'close', title?: string | InputArgs<InputOptions, string | Series>, opts?: InputOptions): Series {
|
|
1393
1817
|
const a = inputArgs<string | Series, InputOptions>('source', defval, title, opts);
|
|
1394
1818
|
const name = registerInput<string>({ type: 'source', defval: sourceName(a.defval ?? 'close'), title: a.title, ...common(a.opts) }, 'input_source');
|
|
1395
1819
|
return sourceSeries(name);
|
|
1396
1820
|
},
|
|
1397
|
-
/**
|
|
1821
|
+
/**
|
|
1822
|
+
* Declares a timeframe setting (a timeframe picker) and returns its value, for `request.security()` or
|
|
1823
|
+
* `timeframe.change()`.
|
|
1824
|
+
* @param defval - Default timeframe: `"60"` (60 minutes), `"D"`, `"W"`, `"M"`...; `""` is the chart's timeframe.
|
|
1825
|
+
* Or every argument by name.
|
|
1826
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_timeframe`).
|
|
1827
|
+
* @param opts - `options` (a choice list of timeframes) and the common input options.
|
|
1828
|
+
* @returns The current timeframe string (`""`: the chart's timeframe).
|
|
1829
|
+
* @example
|
|
1830
|
+
* ```js
|
|
1831
|
+
* const tf = input.timeframe("D", "Higher timeframe");
|
|
1832
|
+
* const htfClose = request.security("", tf, () => close);
|
|
1833
|
+
* ```
|
|
1834
|
+
*/
|
|
1398
1835
|
timeframe(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string {
|
|
1399
1836
|
const a = inputArgs<string, StringInputOptions>('timeframe', defval, title, opts);
|
|
1400
1837
|
return registerInput<string>({ type: 'timeframe', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_timeframe');
|
|
1401
1838
|
},
|
|
1402
|
-
/**
|
|
1839
|
+
/**
|
|
1840
|
+
* Declares a trading-hours setting and returns its value, a session string for `time()` or `inSession()`.
|
|
1841
|
+
* @param defval - Default session: `"HHMM-HHMM"`, optionally followed by `:` and the days (1 = Sunday ...
|
|
1842
|
+
* 7 = Saturday), e.g. `"0930-1600"` or `"0930-1600:23456"`. Or every argument by name.
|
|
1843
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_session`).
|
|
1844
|
+
* @param opts - `options` (a choice list of sessions) and the common input options.
|
|
1845
|
+
* @returns The current session string.
|
|
1846
|
+
* @example
|
|
1847
|
+
* ```js
|
|
1848
|
+
* const sess = input.session("0930-1600", "Session");
|
|
1849
|
+
* bgcolor(color.when(na(time("", sess)).not(), color.new(color.blue, 90)));
|
|
1850
|
+
* ```
|
|
1851
|
+
*/
|
|
1403
1852
|
session(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string {
|
|
1404
1853
|
const a = inputArgs<string, StringInputOptions>('session', defval, title, opts);
|
|
1405
1854
|
return registerInput<string>({ type: 'session', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_session');
|
|
1406
1855
|
},
|
|
1407
|
-
/**
|
|
1856
|
+
/**
|
|
1857
|
+
* Declares a symbol setting (a symbol search) and returns its value, a ticker id for `request.security()` of
|
|
1858
|
+
* another symbol.
|
|
1859
|
+
* @param defval - Default ticker id, `"EXCHANGE:TICKER"` (`"NASDAQ:MSFT"`), or every argument by name.
|
|
1860
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_symbol`).
|
|
1861
|
+
* @param opts - `options` (a choice list of symbols) and the common input options.
|
|
1862
|
+
* @returns The current ticker id.
|
|
1863
|
+
* @example
|
|
1864
|
+
* ```js
|
|
1865
|
+
* const other = input.symbol("NASDAQ:MSFT", "Compare with");
|
|
1866
|
+
* plot(request.security(other, "", () => close), "Other close");
|
|
1867
|
+
* ```
|
|
1868
|
+
*/
|
|
1408
1869
|
symbol(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string {
|
|
1409
1870
|
const a = inputArgs<string, StringInputOptions>('symbol', defval, title, opts);
|
|
1410
1871
|
return registerInput<string>({ type: 'symbol', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_symbol');
|
|
1411
1872
|
},
|
|
1412
1873
|
/**
|
|
1413
|
-
*
|
|
1414
|
-
*
|
|
1874
|
+
* Declares a price-level setting (a number field) and returns its value. With `confirm: true` the host can ask the
|
|
1875
|
+
* user to pick it on the chart; an `inline` id shared with an `input.time()` makes one chart point of both.
|
|
1876
|
+
* @param defval - Default price, or every argument by name.
|
|
1877
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_float`).
|
|
1878
|
+
* @param opts - The common input options.
|
|
1879
|
+
* @returns The current price: the user's value, else `defval`.
|
|
1880
|
+
* @example
|
|
1881
|
+
* ```js
|
|
1882
|
+
* const level = input.price(100, "Level", { confirm: true });
|
|
1883
|
+
* hline(level, "Level");
|
|
1884
|
+
* ```
|
|
1415
1885
|
*/
|
|
1416
1886
|
price(defval: number | InputArgs<InputOptions, number>, title?: string | InputArgs<InputOptions, number>, opts?: InputOptions): number {
|
|
1417
1887
|
const a = inputArgs<number, InputOptions>('price', defval, title, opts);
|
|
1418
1888
|
return registerNumeric('price', a.defval, a.title, a.opts, 'float');
|
|
1419
1889
|
},
|
|
1420
1890
|
/**
|
|
1421
|
-
*
|
|
1422
|
-
*
|
|
1891
|
+
* Declares a choice among the fields of an enum made with `defineEnum()` and returns the chosen field. The
|
|
1892
|
+
* settings list the fields by title; the host stores the field's name.
|
|
1893
|
+
* @param defval - Default field (`MaType.sma`), or every argument by name. It must be one of `options`.
|
|
1894
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_enum`).
|
|
1895
|
+
* @param opts - `options` (only these fields of the enum) and the common input options.
|
|
1896
|
+
* @returns The chosen field; compare it with `===`.
|
|
1897
|
+
* @example
|
|
1898
|
+
* ```js
|
|
1899
|
+
* const MaType = defineEnum({ sma: "Simple", ema: "Exponential" });
|
|
1900
|
+
* const maType = input.enum(MaType.sma, "Average");
|
|
1901
|
+
* const ma = maType === MaType.ema ? ta.ema(close, 20) : ta.sma(close, 20);
|
|
1902
|
+
* ```
|
|
1423
1903
|
*/
|
|
1424
1904
|
enum<F extends EnumField>(defval: F | InputArgs<EnumInputOptions, F>, title?: string | InputArgs<EnumInputOptions, F>, opts?: EnumInputOptions): F {
|
|
1425
1905
|
const a = inputArgs<F, EnumInputOptions>('enum', defval, title, opts);
|
|
@@ -1443,7 +1923,19 @@ export const input = strictNamespace('input', {
|
|
|
1443
1923
|
);
|
|
1444
1924
|
return (choices.find((f) => f.name === name) ?? a.defval) as F;
|
|
1445
1925
|
},
|
|
1446
|
-
/**
|
|
1926
|
+
/**
|
|
1927
|
+
* Declares a date-and-time setting and returns it as a UNIX time in milliseconds. With `confirm: true` the host
|
|
1928
|
+
* can ask the user to pick it on the chart. Shown only in the settings by default.
|
|
1929
|
+
* @param defval - Default time in ms, usually from `timestamp()`, or every argument by name.
|
|
1930
|
+
* @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_time`).
|
|
1931
|
+
* @param opts - The common input options.
|
|
1932
|
+
* @returns The current time in ms: the user's value, else `defval`.
|
|
1933
|
+
* @example
|
|
1934
|
+
* ```js
|
|
1935
|
+
* const start = input.time(timestamp("2024-01-01"), "Start");
|
|
1936
|
+
* bgcolor(color.when(time.gte(start), color.new(color.green, 90)));
|
|
1937
|
+
* ```
|
|
1938
|
+
*/
|
|
1447
1939
|
time(defval: number | InputArgs<InputOptions, number>, title?: string | InputArgs<InputOptions, number>, opts?: InputOptions): number {
|
|
1448
1940
|
const a = inputArgs<number, InputOptions>('time', defval, title, opts);
|
|
1449
1941
|
const v = registerInput<unknown>({ type: 'time', defval: a.defval, title: a.title, ...common(a.opts) }, 'input_time');
|
|
@@ -1453,19 +1945,96 @@ export const input = strictNamespace('input', {
|
|
|
1453
1945
|
|
|
1454
1946
|
// ── OHLCV builtins ───────────────────────────────────────────────────────────
|
|
1455
1947
|
|
|
1948
|
+
/**
|
|
1949
|
+
* Opening price of each bar, as a Series. In a bar loop, `c.open` is the value of the current bar.
|
|
1950
|
+
* @example
|
|
1951
|
+
* ```js
|
|
1952
|
+
* const body = close.sub(open);
|
|
1953
|
+
* plot(body, "Body", { style: plot.style_columns });
|
|
1954
|
+
* ```
|
|
1955
|
+
*/
|
|
1456
1956
|
export const open = Series.fromBars(ctxBars, 'open');
|
|
1957
|
+
/**
|
|
1958
|
+
* Highest price of each bar, as a Series. In a bar loop, `c.high` is the value of the current bar.
|
|
1959
|
+
* @example
|
|
1960
|
+
* ```js
|
|
1961
|
+
* plot(ta.highest(high, 20), "20-bar high");
|
|
1962
|
+
* ```
|
|
1963
|
+
*/
|
|
1457
1964
|
export const high = Series.fromBars(ctxBars, 'high');
|
|
1965
|
+
/**
|
|
1966
|
+
* Lowest price of each bar, as a Series. In a bar loop, `c.low` is the value of the current bar.
|
|
1967
|
+
* @example
|
|
1968
|
+
* ```js
|
|
1969
|
+
* plot(ta.lowest(low, 20), "20-bar low");
|
|
1970
|
+
* ```
|
|
1971
|
+
*/
|
|
1458
1972
|
export const low = Series.fromBars(ctxBars, 'low');
|
|
1973
|
+
/**
|
|
1974
|
+
* Closing price of each bar, as a Series (on the forming bar, the latest price). The usual source of indicators.
|
|
1975
|
+
* In a bar loop, `c.close` is the value of the current bar.
|
|
1976
|
+
* @example
|
|
1977
|
+
* ```js
|
|
1978
|
+
* plot(ta.sma(close, 20), "SMA");
|
|
1979
|
+
* ```
|
|
1980
|
+
*/
|
|
1459
1981
|
export const close = Series.fromBars(ctxBars, 'close');
|
|
1982
|
+
/**
|
|
1983
|
+
* Traded volume of each bar, as a Series (NaN when the data has no volume). In a bar loop, `c.volume`.
|
|
1984
|
+
* @example
|
|
1985
|
+
* ```js
|
|
1986
|
+
* plot(volume, "Volume", { style: plot.style_columns });
|
|
1987
|
+
* ```
|
|
1988
|
+
*/
|
|
1460
1989
|
export const volume = Series.fromBars(ctxBars, 'volume');
|
|
1990
|
+
/**
|
|
1991
|
+
* Median price of each bar, (high + low) / 2, as a Series.
|
|
1992
|
+
* @example
|
|
1993
|
+
* ```js
|
|
1994
|
+
* plot(ta.sma(hl2, 10), "Median SMA");
|
|
1995
|
+
* ```
|
|
1996
|
+
*/
|
|
1461
1997
|
export const hl2 = new Series(ctxBars, (b) => (b.high + b.low) / 2);
|
|
1998
|
+
/**
|
|
1999
|
+
* Typical price of each bar, (high + low + close) / 3, as a Series.
|
|
2000
|
+
* @example
|
|
2001
|
+
* ```js
|
|
2002
|
+
* plot(ta.sma(hlc3, 20), "Typical SMA");
|
|
2003
|
+
* ```
|
|
2004
|
+
*/
|
|
1462
2005
|
export const hlc3 = new Series(ctxBars, (b) => (b.high + b.low + b.close) / 3);
|
|
2006
|
+
/**
|
|
2007
|
+
* Average price of each bar, (open + high + low + close) / 4, as a Series.
|
|
2008
|
+
* @example
|
|
2009
|
+
* ```js
|
|
2010
|
+
* plot(ohlc4, "OHLC average");
|
|
2011
|
+
* ```
|
|
2012
|
+
*/
|
|
1463
2013
|
export const ohlc4 = new Series(ctxBars, (b) => (b.open + b.high + b.low + b.close) / 4);
|
|
2014
|
+
/**
|
|
2015
|
+
* Weighted close of each bar, (high + low + close + close) / 4, as a Series.
|
|
2016
|
+
* @example
|
|
2017
|
+
* ```js
|
|
2018
|
+
* plot(ta.ema(hlcc4, 20), "Weighted close EMA");
|
|
2019
|
+
* ```
|
|
2020
|
+
*/
|
|
1464
2021
|
export const hlcc4 = new Series(ctxBars, (b) => (b.high + b.low + 2 * b.close) / 4);
|
|
1465
|
-
/**
|
|
2022
|
+
/**
|
|
2023
|
+
* 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.
|
|
2024
|
+
* @example
|
|
2025
|
+
* ```js
|
|
2026
|
+
* plotshape(bar_index.mod(10).eq(0), "Every 10 bars", { style: shape.circle });
|
|
2027
|
+
* ```
|
|
2028
|
+
*/
|
|
1466
2029
|
export const bar_index = new Series(ctxBars, (_b, i) => i);
|
|
1467
2030
|
bar_index.fullHistory = true;
|
|
1468
|
-
/**
|
|
2031
|
+
/**
|
|
2032
|
+
* Index of the last bar of the chart, the same on every bar, as a Series. In a bar loop, `c.n - 1`.
|
|
2033
|
+
* @example
|
|
2034
|
+
* ```js
|
|
2035
|
+
* bgcolor(color.when(bar_index.gte(last_bar_index.sub(9)), color.new(color.blue, 90)), { title: "Last 10 bars" });
|
|
2036
|
+
* ```
|
|
2037
|
+
*/
|
|
1469
2038
|
export const last_bar_index = new Series(ctxBars, (_b, _i, data) => {
|
|
1470
2039
|
// the same value on every bar, changed by a new bar: not kept by an incremental run (#196), but the same in the
|
|
1471
2040
|
// intrabar runs of a backtest (the chart's last bar, #206)
|
|
@@ -1536,6 +2105,12 @@ function editDistance(a: string, b: string): number {
|
|
|
1536
2105
|
/** Names a tool reads to probe an object (promise, JSON, test matchers, module interop): never an error. */
|
|
1537
2106
|
const PROBED_NAMES = new Set(['then', 'toJSON', 'asymmetricMatch', 'nodeType', 'tagName', 'inspect', 'default']);
|
|
1538
2107
|
|
|
2108
|
+
/**
|
|
2109
|
+
* Compile-time check that a namespace's documented interface lists exactly the members of its implementation: a
|
|
2110
|
+
* member added to one but not the other makes the call fail to type-check (the argument becomes `false`).
|
|
2111
|
+
*/
|
|
2112
|
+
function sameKeys<A, B>(_same: [Exclude<keyof A, keyof B>, Exclude<keyof B, keyof A>] extends [never, never] ? true : false): void {}
|
|
2113
|
+
|
|
1539
2114
|
/**
|
|
1540
2115
|
* A namespace whose unknown members throw instead of being `undefined`: `ta.smaa(close, 5)` fails with
|
|
1541
2116
|
* "ta.smaa does not exist. Did you mean ta.sma?" rather than "ta.smaa is not a function", and `color.purpel`
|
|
@@ -1571,7 +2146,7 @@ function strictNamespace<T extends object>(name: string, members: T): T {
|
|
|
1571
2146
|
* every bar (slow) and returns a Series, not the value of the bar, and it has no per-bar history: the call throws
|
|
1572
2147
|
* with the fix.
|
|
1573
2148
|
*/
|
|
1574
|
-
function outsideBarLoops<T extends Record<string, unknown>>(members: T): T {
|
|
2149
|
+
function outsideBarLoops<T extends Record<string, unknown>>(members: T, ns = 'ta'): T {
|
|
1575
2150
|
const out: Record<string, unknown> = {};
|
|
1576
2151
|
for (const [key, value] of Object.entries(members)) {
|
|
1577
2152
|
if (typeof value !== 'function') {
|
|
@@ -1582,8 +2157,8 @@ function outsideBarLoops<T extends Record<string, unknown>>(members: T): T {
|
|
|
1582
2157
|
out[key] = function (this: unknown, ...args: unknown[]) {
|
|
1583
2158
|
if (currentBar >= 0) {
|
|
1584
2159
|
throw new Error(
|
|
1585
|
-
|
|
1586
|
-
`Compute it before the loop (const x =
|
|
2160
|
+
`${ns}.${key}() was called inside eachBar(): a ${ns}.* call computes the whole Series at once. ` +
|
|
2161
|
+
`Compute it before the loop (const x = ${ns}.${key}(...)) and read the bar's value with c.get(x). ` +
|
|
1587
2162
|
'For a Pine ta.* call inside an if block or a for loop, use the callsite.* call sites.'
|
|
1588
2163
|
);
|
|
1589
2164
|
}
|
|
@@ -1714,10 +2289,14 @@ const steppedTa = {
|
|
|
1714
2289
|
() => taSeries.stoch(source, highSource, lowSource, length)),
|
|
1715
2290
|
};
|
|
1716
2291
|
|
|
2292
|
+
// The library's own `ta` object (bars-first functions) is not a script member.
|
|
2293
|
+
const { ta: _libraryTa, ...taFunctions } = taSeries;
|
|
2294
|
+
void _libraryTa;
|
|
2295
|
+
|
|
1717
2296
|
/** ta.* with the chart-implicit (bars-first) functions bound to the context,
|
|
1718
|
-
* so scripts call them like
|
|
1719
|
-
|
|
1720
|
-
...
|
|
2297
|
+
* so scripts call them like `ta.tr(true)`, `ta.atr(14)`. Its members and their documentation: {@link TaNamespace}. */
|
|
2298
|
+
const taMembers = strictNamespace('ta', outsideBarLoops({
|
|
2299
|
+
...taFunctions,
|
|
1721
2300
|
...steppedTa,
|
|
1722
2301
|
tr: (handleNa: boolean = false): Series =>
|
|
1723
2302
|
stepped('tr', () => taStep.tr(handleNa), [high, low, close], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1, () =>
|
|
@@ -1811,11 +2390,43 @@ export const ta = strictNamespace('ta', outsideBarLoops({
|
|
|
1811
2390
|
iii: barsSeries(taSeries.iii),
|
|
1812
2391
|
wad: barsSeries(taSeries.wad),
|
|
1813
2392
|
wvad: barsSeries(taSeries.wvad),
|
|
2393
|
+
zigzag: (deviation?: number, depth?: number, backstep?: number): [Series, Series, Series] =>
|
|
2394
|
+
taSeries.zigzag(bars(), deviation, depth, backstep),
|
|
1814
2395
|
}));
|
|
2396
|
+
/**
|
|
2397
|
+
* Technical analysis: moving averages, oscillators, bands, crosses, pivots and volume indicators. Each function
|
|
2398
|
+
* computes a whole Series in one call: call it before any `eachBar()` loop and read a bar's value with `c.get(x)`.
|
|
2399
|
+
* @example
|
|
2400
|
+
* ```js
|
|
2401
|
+
* const fast = ta.ema(close, 12), slow = ta.ema(close, 26);
|
|
2402
|
+
* plot(fast, "Fast"); plot(slow, "Slow");
|
|
2403
|
+
* ```
|
|
2404
|
+
*/
|
|
2405
|
+
export const ta: TaNamespace = taMembers;
|
|
2406
|
+
sameKeys<typeof taMembers, TaNamespace>(true);
|
|
1815
2407
|
|
|
1816
|
-
/**
|
|
1817
|
-
*
|
|
2408
|
+
/**
|
|
2409
|
+
* Fills the gaps of a Series: each na value (NaN) becomes the last value that was not na. Values before the first
|
|
2410
|
+
* non-na value stay na; +/-Infinity is kept.
|
|
2411
|
+
* @param source - The Series to fill.
|
|
2412
|
+
* @returns A Series without gaps after its first value.
|
|
2413
|
+
* @example
|
|
2414
|
+
* ```js
|
|
2415
|
+
* const pivot = fixnan(ta.pivothigh(5, 5));
|
|
2416
|
+
* plot(pivot, "Last pivot high", { style: plot.style_stepline });
|
|
2417
|
+
* ```
|
|
2418
|
+
*/
|
|
1818
2419
|
export function fixnan(source: Series): Series;
|
|
2420
|
+
/**
|
|
2421
|
+
* Fills the gaps of a per-bar colour array: each na entry (`undefined`) becomes the last colour that was not na.
|
|
2422
|
+
* @param source - One colour per bar, as made by `color.when()`.
|
|
2423
|
+
* @returns A colour array without gaps after its first colour.
|
|
2424
|
+
* @example
|
|
2425
|
+
* ```js
|
|
2426
|
+
* const trendColor = fixnan(color.when(ta.crossover(close, ta.sma(close, 20)), color.green));
|
|
2427
|
+
* barcolor(trendColor);
|
|
2428
|
+
* ```
|
|
2429
|
+
*/
|
|
1819
2430
|
export function fixnan(source: Array<string | undefined>): Array<string | undefined>;
|
|
1820
2431
|
export function fixnan(source: Series | Array<string | undefined>): Series | Array<string | undefined> {
|
|
1821
2432
|
if (source instanceof Series) return Series.fromArray(ctxBars, fixnanValues(source.toArray()));
|
|
@@ -1823,20 +2434,58 @@ export function fixnan(source: Series | Array<string | undefined>): Series | Arr
|
|
|
1823
2434
|
return withPalette(fixnanValues(source), colorPalettes.get(source));
|
|
1824
2435
|
}
|
|
1825
2436
|
|
|
1826
|
-
/**
|
|
1827
|
-
*
|
|
1828
|
-
*
|
|
2437
|
+
/**
|
|
2438
|
+
* Tells, bar by bar, whether a Series is na (NaN or +/-Infinity): a Series of 1 where it is, 0 elsewhere.
|
|
2439
|
+
* @param x - The Series to test.
|
|
2440
|
+
* @returns A Series of 1 / 0.
|
|
2441
|
+
* @example
|
|
2442
|
+
* ```js
|
|
2443
|
+
* const ma = ta.sma(close, 50);
|
|
2444
|
+
* bgcolor(color.when(na(ma), color.new(color.gray, 90)), { title: "Warming up" });
|
|
2445
|
+
* ```
|
|
2446
|
+
*/
|
|
1829
2447
|
export function na(x: Series): Series;
|
|
2448
|
+
/**
|
|
2449
|
+
* Tells whether one value is na: NaN, +/-Infinity, `undefined` or `null` (a colour or a drawing), a deleted drawing,
|
|
2450
|
+
* or an empty text. Use it on the numbers of a bar loop.
|
|
2451
|
+
* @param x - The value to test.
|
|
2452
|
+
* @returns true when the value is na.
|
|
2453
|
+
* @example
|
|
2454
|
+
* ```js
|
|
2455
|
+
* const ma = ta.sma(close, 50);
|
|
2456
|
+
* eachBar((c) => { if (!na(c.get(ma)) && c.close > c.get(ma)) label.new(c.i, c.high, "Above"); });
|
|
2457
|
+
* ```
|
|
2458
|
+
*/
|
|
1830
2459
|
export function na(x: unknown): boolean;
|
|
1831
2460
|
export function na(x: unknown): Series | boolean {
|
|
1832
2461
|
if (x instanceof Series) return Series.fromArray(ctxBars, x.toArray().map((v) => (isNA(v) ? 1 : 0)));
|
|
1833
2462
|
return x === '' || isNA(x);
|
|
1834
2463
|
}
|
|
1835
2464
|
|
|
1836
|
-
/**
|
|
1837
|
-
*
|
|
1838
|
-
*
|
|
2465
|
+
/**
|
|
2466
|
+
* Replaces the na values of a Series (NaN or +/-Infinity) with a replacement, bar by bar, e.g. to start a sum at 0.
|
|
2467
|
+
* @param source - The Series to clean.
|
|
2468
|
+
* @param replacement - The value for the na bars: a number, or a Series (its value on the same bar). Default: 0.
|
|
2469
|
+
* @returns A Series without na values (unless the replacement is na).
|
|
2470
|
+
* @example
|
|
2471
|
+
* ```js
|
|
2472
|
+
* const change = nz(close.sub(close.offset(1)));
|
|
2473
|
+
* plot(change, "Change", { style: plot.style_columns });
|
|
2474
|
+
* ```
|
|
2475
|
+
*/
|
|
1839
2476
|
export function nz(source: Series, replacement?: number | Series): Series;
|
|
2477
|
+
/**
|
|
2478
|
+
* Returns a value, or a replacement when it is na (NaN, +/-Infinity, `undefined`, `null`). Use it on the numbers of
|
|
2479
|
+
* a bar loop.
|
|
2480
|
+
* @param source - The value to check.
|
|
2481
|
+
* @param replacement - The value returned when `source` is na. Default: 0.
|
|
2482
|
+
* @returns `source`, or `replacement` when `source` is na.
|
|
2483
|
+
* @example
|
|
2484
|
+
* ```js
|
|
2485
|
+
* const total = eachBar((c) => nz(c.prev()) + c.volume);
|
|
2486
|
+
* plot(total, "Cumulative volume");
|
|
2487
|
+
* ```
|
|
2488
|
+
*/
|
|
1840
2489
|
export function nz<T>(source: T, replacement?: T): T;
|
|
1841
2490
|
export function nz(source: unknown, replacement: unknown = 0): unknown {
|
|
1842
2491
|
if (source instanceof Series) {
|
|
@@ -1917,58 +2566,123 @@ function fromGradient(
|
|
|
1917
2566
|
);
|
|
1918
2567
|
}
|
|
1919
2568
|
|
|
1920
|
-
|
|
1921
|
-
export const color = strictNamespace('color', {
|
|
2569
|
+
const colorMembers = strictNamespace('color', {
|
|
1922
2570
|
...colorCore,
|
|
1923
2571
|
new: colorCore.new_color,
|
|
1924
2572
|
from_gradient: fromGradient,
|
|
1925
2573
|
when: colorWhen,
|
|
2574
|
+
/**
|
|
2575
|
+
* Not in PineScript: the colour faded by `amount`, from 0 (unchanged) to 1 (invisible): `color.fade(color.red, 0.8)`
|
|
2576
|
+
* is `color.new(color.red, 80)`.
|
|
2577
|
+
*/
|
|
2578
|
+
fade: (c: string, amount: number): string => {
|
|
2579
|
+
if (typeof amount !== 'number' || !(amount >= 0 && amount <= 1)) {
|
|
2580
|
+
throw new ScriptError(`color.fade(): the amount is from 0 (unchanged) to 1 (invisible), got ${shown(amount)}.`);
|
|
2581
|
+
}
|
|
2582
|
+
return colorCore.new_color(c, amount * 100);
|
|
2583
|
+
},
|
|
1926
2584
|
});
|
|
2585
|
+
/**
|
|
2586
|
+
* Colours: named colours (`color.red`, `color.teal`...), `color.new` for transparency, `color.rgb`, gradients, and
|
|
2587
|
+
* `color.when` to pick a colour per bar for `plot()`, `fill()`, `bgcolor()` and `barcolor()`.
|
|
2588
|
+
* @example
|
|
2589
|
+
* ```js
|
|
2590
|
+
* const up = close.gt(open);
|
|
2591
|
+
* plot(close, "Close", { color: color.when(up, color.green, color.red) });
|
|
2592
|
+
* bgcolor(color.new(color.blue, 90));
|
|
2593
|
+
* ```
|
|
2594
|
+
*/
|
|
2595
|
+
export const color: ColorNamespace = colorMembers;
|
|
2596
|
+
sameKeys<typeof colorMembers, ColorNamespace>(true);
|
|
1927
2597
|
|
|
1928
2598
|
// ── Drawing declarations ─────────────────────────────────────────────────────
|
|
1929
2599
|
|
|
2600
|
+
/** Options of {@link plot}. */
|
|
1930
2601
|
export interface ScriptPlotOptions {
|
|
1931
|
-
/** Shift in bars
|
|
2602
|
+
/** Shift in bars: the value of bar i is drawn on bar i + offset (negative: to the left). Default: 0. */
|
|
1932
2603
|
offset?: number;
|
|
1933
|
-
/**
|
|
2604
|
+
/** One colour, or one colour per bar (`color.when()`, `undefined` = not drawn). Default: blue `#2962FF`. */
|
|
1934
2605
|
color?: string | string[];
|
|
2606
|
+
/** Line width in pixels. Default: 1. */
|
|
1935
2607
|
linewidth?: number;
|
|
2608
|
+
/** How the values are drawn: `plot.style_line`, `plot.style_histogram`, `plot.style_columns`... Default: `plot.style_line`. */
|
|
1936
2609
|
style?: PlotConfig['style'];
|
|
1937
|
-
/**
|
|
2610
|
+
/** Dash pattern of the line: `plot.linestyle_solid`, `plot.linestyle_dashed` or `plot.linestyle_dotted` (one for all bars). Default: solid. */
|
|
1938
2611
|
linestyle?: PlotConfig['linestyle'];
|
|
2612
|
+
/** Where the plot shows: `display.all`, `display.none` (hidden, still listed), `display.pane`, `display.status_line`, `display.data_window`. Default: `display.all`. */
|
|
1939
2613
|
display?: PlotConfig['display'];
|
|
2614
|
+
/** Base level the histogram bars start from (`plot.style_histogram`). Default: 0. */
|
|
1940
2615
|
histbase?: number;
|
|
1941
|
-
/**
|
|
2616
|
+
/** true: draw on the price pane even when the script has its own pane. Default: false. */
|
|
1942
2617
|
force_overlay?: boolean;
|
|
1943
|
-
/**
|
|
2618
|
+
/** false: not listed in the style settings of the script. Default: true. */
|
|
1944
2619
|
editable?: boolean;
|
|
1945
2620
|
}
|
|
1946
2621
|
|
|
1947
2622
|
/**
|
|
1948
|
-
*
|
|
1949
|
-
*
|
|
2623
|
+
* The titles an output gets when the script gives none (`plot` is "Plot", `hline` is "Level"...): the style settings
|
|
2624
|
+
* and the alert lists show them.
|
|
1950
2625
|
*/
|
|
1951
2626
|
export const DEFAULT_OUTPUT_TITLES = {
|
|
2627
|
+
/** Title of a `plot()` without one. */
|
|
1952
2628
|
plot: 'Plot',
|
|
2629
|
+
/** Title of an `hline()` without one. */
|
|
1953
2630
|
hline: 'Level',
|
|
2631
|
+
/** Title of a `fill()` between two plots without one. */
|
|
1954
2632
|
plotFill: 'Plots Background',
|
|
2633
|
+
/** Title of a `fill()` between two hlines without one. */
|
|
1955
2634
|
hlineFill: 'Hlines Background',
|
|
2635
|
+
/** Title of a `plotshape()` without one. */
|
|
1956
2636
|
shape: 'Shapes',
|
|
2637
|
+
/** Title of a `plotchar()` without one. */
|
|
1957
2638
|
char: 'Chars',
|
|
2639
|
+
/** Title of a `plotarrow()` without one. */
|
|
1958
2640
|
arrow: 'Arrows',
|
|
2641
|
+
/** Title of a `bgcolor()` without one. */
|
|
1959
2642
|
bgcolor: 'Background Color',
|
|
2643
|
+
/** Title of a `barcolor()` without one. */
|
|
1960
2644
|
barcolor: 'Bar Color',
|
|
2645
|
+
/** Title of a `plotcandle()` without one. */
|
|
1961
2646
|
candle: 'PlotCandle',
|
|
2647
|
+
/** Title of a `plotbar()` without one. */
|
|
1962
2648
|
bar: 'PlotBar',
|
|
1963
2649
|
} as const;
|
|
1964
2650
|
|
|
1965
|
-
|
|
1966
|
-
|
|
2651
|
+
const PLOT_OPTION_KEYS = ['offset', 'color', 'linewidth', 'style', 'linestyle', 'display', 'histbase', 'force_overlay', 'editable'] as const;
|
|
2652
|
+
|
|
2653
|
+
/**
|
|
2654
|
+
* Draws a Series on the chart (a line by default, or a histogram, columns, area, circles...) and lists it in the
|
|
2655
|
+
* legend and the settings. Bars whose value is na (NaN or +/-Infinity) are not drawn.
|
|
2656
|
+
* @param source - The values to draw: a Series, or a number for the same value on every bar.
|
|
2657
|
+
* @param title - Name of the plot in the legend, the settings and the alerts. Default: "Plot".
|
|
2658
|
+
* @param options - Colour, width, style, line style, offset, display... Default: `{}` (a blue line).
|
|
2659
|
+
* @returns A handle to pass to `fill()`.
|
|
2660
|
+
* @example
|
|
2661
|
+
* ```js
|
|
2662
|
+
* const fast = plot(ta.ema(close, 12), "Fast", { color: color.teal, linewidth: 2 });
|
|
2663
|
+
* const slow = plot(ta.ema(close, 26), "Slow", { color: color.orange });
|
|
2664
|
+
* fill(fast, slow, color.new(color.gray, 85));
|
|
2665
|
+
* ```
|
|
2666
|
+
*/
|
|
2667
|
+
function plotImpl(source: Series | number, title: string = DEFAULT_OUTPUT_TITLES.plot, options: ScriptPlotOptions = {}): PlotHandle {
|
|
1967
2668
|
if (intrabarRun) return { id: '', kind: 'plot' }; // dropped: an intrabar run's outputs aren't read
|
|
1968
2669
|
const c = collector();
|
|
1969
|
-
|
|
2670
|
+
if (c.strict && typeof title !== 'string') throw new ScriptError(`plot(): the title is a text, e.g. plot(rsi, "RSI"), got ${shown(title)}.`);
|
|
2671
|
+
checkOptions('plot', options, PLOT_OPTION_KEYS);
|
|
2672
|
+
const series = typeof source === 'number' ? new Series(ctxBars, () => source) : source;
|
|
2673
|
+
if (!(series instanceof Series)) {
|
|
2674
|
+
throw new TypeError(`plot(): the value to plot is a series (close, ta.sma(close, 14)...) or a number, got ${shown(source)}.`);
|
|
2675
|
+
}
|
|
2676
|
+
const id = scriptOptions.plotIds === 'title' ? slugId(title, `plot${c.plotConfig.length}`, (c.plotIdsTaken ??= new Set())) : `plot${c.plotConfig.length}`;
|
|
1970
2677
|
const perBar = Array.isArray(options.color) ? options.color : undefined;
|
|
1971
|
-
const
|
|
2678
|
+
const palette = scriptOptions.palette === true ? DEFAULT_PALETTE : Array.isArray(scriptOptions.palette) && scriptOptions.palette.length ? scriptOptions.palette : null;
|
|
2679
|
+
let fallback = '#2962FF';
|
|
2680
|
+
if (palette && options.color === undefined) {
|
|
2681
|
+
const k = c.paletteUsed ?? 0;
|
|
2682
|
+
c.paletteUsed = k + 1;
|
|
2683
|
+
fallback = palette[k % palette.length]!;
|
|
2684
|
+
}
|
|
2685
|
+
const staticColor = typeof options.color === 'string' ? options.color : (perBar?.[perBar.length - 1] ?? fallback);
|
|
1972
2686
|
c.plotConfig.push({
|
|
1973
2687
|
id,
|
|
1974
2688
|
title,
|
|
@@ -2021,11 +2735,57 @@ function plotImpl(series: Series, title: string = DEFAULT_OUTPUT_TITLES.plot, op
|
|
|
2021
2735
|
return { id, kind: 'plot' };
|
|
2022
2736
|
}
|
|
2023
2737
|
|
|
2738
|
+
/** The `plot()` function with its `plot.style_*` and `plot.linestyle_*` constants. */
|
|
2739
|
+
export interface PlotFunction {
|
|
2740
|
+
/**
|
|
2741
|
+
* Draws a Series on the chart (a line by default, or a histogram, columns, area, circles...) and lists it in the
|
|
2742
|
+
* legend and the settings. Bars whose value is na (NaN or +/-Infinity) are not drawn.
|
|
2743
|
+
* @param source - The values to draw: a Series, or a number for the same value on every bar.
|
|
2744
|
+
* @param title - Name of the plot in the legend, the settings and the alerts. Default: "Plot".
|
|
2745
|
+
* @param options - Colour, width, style, line style, offset, display... Default: `{}` (a blue line).
|
|
2746
|
+
* @returns A handle to pass to `fill()`.
|
|
2747
|
+
*/
|
|
2748
|
+
(source: Series | number, title?: string, options?: ScriptPlotOptions): PlotHandle;
|
|
2749
|
+
/** Style: a line through every value; na values are bridged. */
|
|
2750
|
+
readonly style_line: 'line';
|
|
2751
|
+
/** Style: a line with a gap where the value is na. */
|
|
2752
|
+
readonly style_linebr: 'linebr';
|
|
2753
|
+
/** Style: steps (horizontal then vertical moves); na values are bridged. */
|
|
2754
|
+
readonly style_stepline: 'stepline';
|
|
2755
|
+
/** Style: steps with a gap where the value is na. */
|
|
2756
|
+
readonly style_steplinebr: 'steplinebr';
|
|
2757
|
+
/** Style: steps with a diamond on each change. */
|
|
2758
|
+
readonly style_stepline_diamond: 'stepline_diamond';
|
|
2759
|
+
/** Style: a thin bar from the base line (`histbase`, default 0) to each value. */
|
|
2760
|
+
readonly style_histogram: 'histogram';
|
|
2761
|
+
/** Style: a wide column from the base line to each value. */
|
|
2762
|
+
readonly style_columns: 'columns';
|
|
2763
|
+
/** Style: a line with the area down to the base line filled. */
|
|
2764
|
+
readonly style_area: 'area';
|
|
2765
|
+
/** Style: a filled area with a gap where the value is na. */
|
|
2766
|
+
readonly style_areabr: 'areabr';
|
|
2767
|
+
/** Style: a dot on each value. */
|
|
2768
|
+
readonly style_circles: 'circles';
|
|
2769
|
+
/** Style: a cross on each value. */
|
|
2770
|
+
readonly style_cross: 'cross';
|
|
2771
|
+
/** Line style: solid. */
|
|
2772
|
+
readonly linestyle_solid: 'solid';
|
|
2773
|
+
/** Line style: dotted. */
|
|
2774
|
+
readonly linestyle_dotted: 'dotted';
|
|
2775
|
+
/** Line style: dashed. */
|
|
2776
|
+
readonly linestyle_dashed: 'dashed';
|
|
2777
|
+
}
|
|
2778
|
+
|
|
2024
2779
|
/**
|
|
2025
|
-
*
|
|
2026
|
-
*
|
|
2780
|
+
* Draws a Series on the chart and lists it in the legend and the settings; `plot.style_*` and `plot.linestyle_*`
|
|
2781
|
+
* pick how it is drawn.
|
|
2782
|
+
* @example
|
|
2783
|
+
* ```js
|
|
2784
|
+
* const fast = plot(ta.ema(close, 12), "Fast", { color: color.teal, linewidth: 2 });
|
|
2785
|
+
* plot(ta.rsi(close, 14), "RSI", { style: plot.style_histogram });
|
|
2786
|
+
* ```
|
|
2027
2787
|
*/
|
|
2028
|
-
export const plot = Object.assign(plotImpl, {
|
|
2788
|
+
export const plot: PlotFunction = Object.assign(plotImpl, {
|
|
2029
2789
|
style_line: 'line',
|
|
2030
2790
|
style_linebr: 'linebr',
|
|
2031
2791
|
style_stepline: 'stepline',
|
|
@@ -2043,17 +2803,26 @@ export const plot = Object.assign(plotImpl, {
|
|
|
2043
2803
|
} as const);
|
|
2044
2804
|
|
|
2045
2805
|
export interface ScriptHLineOptions {
|
|
2806
|
+
/** Colour of the line. Default: the host's (grey). */
|
|
2046
2807
|
color?: string;
|
|
2047
|
-
/** Line style
|
|
2808
|
+
/** Line style: `hline.style_solid`, `hline.style_dotted` or `hline.style_dashed`. Default: dashed. */
|
|
2048
2809
|
linestyle?: HLineConfig['linestyle'];
|
|
2810
|
+
/** Width of the line in pixels. Default: 1. */
|
|
2049
2811
|
linewidth?: number;
|
|
2050
|
-
/**
|
|
2812
|
+
/** false: not listed in the style settings of the script. Default: true. */
|
|
2051
2813
|
editable?: boolean;
|
|
2052
2814
|
}
|
|
2053
2815
|
|
|
2054
|
-
/**
|
|
2816
|
+
/**
|
|
2817
|
+
* Draws a horizontal line at a fixed price (a level such as 70 / 30 on an oscillator).
|
|
2818
|
+
* @param price - Price of the line.
|
|
2819
|
+
* @param title - Name of the line in the settings. Default: "Level".
|
|
2820
|
+
* @param options - Colour, line style and width. Default: `{}` (a dashed line).
|
|
2821
|
+
* @returns A handle to pass to `fill()`.
|
|
2822
|
+
*/
|
|
2055
2823
|
function hlineImpl(price: number, title: string = DEFAULT_OUTPUT_TITLES.hline, options: ScriptHLineOptions = {}): PlotHandle {
|
|
2056
2824
|
const c = collector();
|
|
2825
|
+
checkOptions('hline', options, ['color', 'linestyle', 'linewidth', 'editable']);
|
|
2057
2826
|
const id = `hline${c.hlineConfig.length}`;
|
|
2058
2827
|
c.hlineConfig.push({
|
|
2059
2828
|
id,
|
|
@@ -2067,18 +2836,45 @@ function hlineImpl(price: number, title: string = DEFAULT_OUTPUT_TITLES.hline, o
|
|
|
2067
2836
|
return { id, kind: 'hline' };
|
|
2068
2837
|
}
|
|
2069
2838
|
|
|
2070
|
-
/**
|
|
2071
|
-
export
|
|
2839
|
+
/** The `hline()` function with its `hline.style_*` constants. */
|
|
2840
|
+
export interface HlineFunction {
|
|
2841
|
+
/**
|
|
2842
|
+
* Draws a horizontal line at a fixed price (a level such as 70 / 30 on an oscillator).
|
|
2843
|
+
* @param price - Price of the line.
|
|
2844
|
+
* @param title - Name of the line in the settings. Default: "Level".
|
|
2845
|
+
* @param options - Colour, line style and width. Default: `{}` (a dashed line).
|
|
2846
|
+
* @returns A handle to pass to `fill()`.
|
|
2847
|
+
*/
|
|
2848
|
+
(price: number, title?: string, options?: ScriptHLineOptions): PlotHandle;
|
|
2849
|
+
/** Line style: solid. */
|
|
2850
|
+
readonly style_solid: 'solid';
|
|
2851
|
+
/** Line style: dotted. */
|
|
2852
|
+
readonly style_dotted: 'dotted';
|
|
2853
|
+
/** Line style: dashed (the default). */
|
|
2854
|
+
readonly style_dashed: 'dashed';
|
|
2855
|
+
}
|
|
2856
|
+
|
|
2857
|
+
/**
|
|
2858
|
+
* Draws a horizontal line at a fixed price; `hline.style_*` picks its line style.
|
|
2859
|
+
* @example
|
|
2860
|
+
* ```js
|
|
2861
|
+
* const top = hline(70, "Overbought", { color: color.red });
|
|
2862
|
+
* const bottom = hline(30, "Oversold", { linestyle: hline.style_dotted });
|
|
2863
|
+
* fill(top, bottom, color.new(color.purple, 90));
|
|
2864
|
+
* ```
|
|
2865
|
+
*/
|
|
2866
|
+
export const hline: HlineFunction = Object.assign(hlineImpl, {
|
|
2072
2867
|
style_solid: 'solid',
|
|
2073
2868
|
style_dotted: 'dotted',
|
|
2074
2869
|
style_dashed: 'dashed',
|
|
2075
2870
|
} as const);
|
|
2076
2871
|
|
|
2077
2872
|
export interface ScriptFillOptions {
|
|
2078
|
-
/**
|
|
2873
|
+
/** Fill colour: one colour, or one per bar from `color.when()`. */
|
|
2079
2874
|
color?: string | string[];
|
|
2875
|
+
/** Name of the fill in the settings. Default: "Plots Background" / "Hlines Background". */
|
|
2080
2876
|
title?: string;
|
|
2081
|
-
/**
|
|
2877
|
+
/** false: not listed in the style settings of the script. Default: true. */
|
|
2082
2878
|
editable?: boolean;
|
|
2083
2879
|
}
|
|
2084
2880
|
|
|
@@ -2104,16 +2900,51 @@ function sameColor(colors: Array<string | null>): string | undefined {
|
|
|
2104
2900
|
}
|
|
2105
2901
|
|
|
2106
2902
|
/**
|
|
2107
|
-
*
|
|
2108
|
-
* -
|
|
2109
|
-
*
|
|
2110
|
-
*
|
|
2111
|
-
*
|
|
2112
|
-
*
|
|
2113
|
-
*
|
|
2903
|
+
* Colours the space between two plots or two hlines, with an options object.
|
|
2904
|
+
* @param a - First plot or hline (the handle `plot()` / `hline()` returned).
|
|
2905
|
+
* @param b - Second plot or hline, of the same kind as `a`.
|
|
2906
|
+
* @param options - Colour (one, or one per bar from `color.when()`), title, editable. Default: `{}`.
|
|
2907
|
+
* @example
|
|
2908
|
+
* ```js
|
|
2909
|
+
* const upper = plot(ta.sma(high, 20), "Upper");
|
|
2910
|
+
* const lower = plot(ta.sma(low, 20), "Lower");
|
|
2911
|
+
* fill(upper, lower, { color: color.new(color.blue, 85), title: "Channel" });
|
|
2912
|
+
* ```
|
|
2114
2913
|
*/
|
|
2115
2914
|
export function fill(a: PlotHandle, b: PlotHandle, options?: ScriptFillOptions): void;
|
|
2915
|
+
/**
|
|
2916
|
+
* Colours the space between two plots or two hlines with one colour (or one per bar).
|
|
2917
|
+
* @param a - First plot or hline (the handle `plot()` / `hline()` returned).
|
|
2918
|
+
* @param b - Second plot or hline, of the same kind as `a`.
|
|
2919
|
+
* @param color - Fill colour, or one per bar from `color.when()`; na (null) leaves a bar unfilled.
|
|
2920
|
+
* @param title - Name of the fill in the settings. Default: "Plots Background" / "Hlines Background".
|
|
2921
|
+
* @param rest - `editable` (false keeps it out of the settings); `show_last`, `fillgaps` and `display` are accepted
|
|
2922
|
+
* and not used.
|
|
2923
|
+
* @example
|
|
2924
|
+
* ```js
|
|
2925
|
+
* const top = hline(70), bottom = hline(30);
|
|
2926
|
+
* fill(top, bottom, color.new(color.purple, 90), "Zone");
|
|
2927
|
+
* ```
|
|
2928
|
+
*/
|
|
2116
2929
|
export function fill(a: PlotHandle, b: PlotHandle, color: ScriptFillColor, title?: string, ...rest: unknown[]): void;
|
|
2930
|
+
/**
|
|
2931
|
+
* Colours the space between two plots with a gradient: `top_color` at `top_value`, `bottom_color` at
|
|
2932
|
+
* `bottom_value`; the values and colours may change from bar to bar.
|
|
2933
|
+
* @param a - First plot (the handle `plot()` returned).
|
|
2934
|
+
* @param b - Second plot.
|
|
2935
|
+
* @param top_value - Price of the top colour: a number or a Series.
|
|
2936
|
+
* @param bottom_value - Price of the bottom colour: a number or a Series.
|
|
2937
|
+
* @param top_color - Colour at the top, or one per bar.
|
|
2938
|
+
* @param bottom_color - Colour at the bottom, or one per bar.
|
|
2939
|
+
* @param title - Name of the fill in the settings. Default: "Plots Background".
|
|
2940
|
+
* @param rest - `editable` (false keeps it out of the settings); other arguments are accepted and not used.
|
|
2941
|
+
* @example
|
|
2942
|
+
* ```js
|
|
2943
|
+
* const basis = ta.sma(close, 20);
|
|
2944
|
+
* const p = plot(close), q = plot(basis);
|
|
2945
|
+
* fill(p, q, high, basis, color.green, color.new(color.green, 100));
|
|
2946
|
+
* ```
|
|
2947
|
+
*/
|
|
2117
2948
|
export function fill(
|
|
2118
2949
|
a: PlotHandle,
|
|
2119
2950
|
b: PlotHandle,
|
|
@@ -2318,27 +3149,56 @@ function emitMarkers(
|
|
|
2318
3149
|
}
|
|
2319
3150
|
}
|
|
2320
3151
|
|
|
2321
|
-
|
|
3152
|
+
const SHAPE_OPTION_KEYS = ['style', 'location', 'color', 'text', 'textcolor', 'size', 'offset', 'tooltip', 'force_overlay', 'editable'] as const;
|
|
3153
|
+
|
|
3154
|
+
/**
|
|
3155
|
+
* Draws a shape (triangle, arrow, circle, label...) on each bar where the condition is true: buy and sell signals.
|
|
3156
|
+
* @param condition - Series that is true (non-zero) on the bars that get a shape. With `location.absolute`, its
|
|
3157
|
+
* value is the price of the shape.
|
|
3158
|
+
* @param title - Name of the shapes in the settings and the alerts. Default: "Shapes".
|
|
3159
|
+
* @param options - Shape (`shape.*`), place (`location.*`), colour, text, size (`size.*`), offset... Default: `{}`
|
|
3160
|
+
* (a cross above the bar).
|
|
3161
|
+
* @example
|
|
3162
|
+
* ```js
|
|
3163
|
+
* const up = ta.crossover(ta.ema(close, 9), ta.ema(close, 21));
|
|
3164
|
+
* plotshape(up, "Buy", { style: shape.triangleup, location: location.belowbar, color: color.green });
|
|
3165
|
+
* ```
|
|
3166
|
+
*/
|
|
2322
3167
|
export function plotshape(condition: Series, title?: string, options: PlotShapeOptions = {}): void {
|
|
3168
|
+
checkOptions('plotshape', options, SHAPE_OPTION_KEYS, ['color', 'textcolor']);
|
|
2323
3169
|
emitMarkers('shape', condition, title, options);
|
|
2324
3170
|
}
|
|
2325
3171
|
|
|
2326
|
-
/**
|
|
3172
|
+
/**
|
|
3173
|
+
* Draws a character (a letter, an emoji...) on each bar where the condition is true.
|
|
3174
|
+
* @param condition - Series that is true (non-zero) on the bars that get the character. With `location.absolute`,
|
|
3175
|
+
* its value is the price of the character.
|
|
3176
|
+
* @param title - Name of the characters in the settings and the alerts. Default: "Chars".
|
|
3177
|
+
* @param options - Character (`char`), place (`location.*`), colour, text, size (`size.*`), offset... Default: `{}`
|
|
3178
|
+
* (a star above the bar).
|
|
3179
|
+
* @example
|
|
3180
|
+
* ```js
|
|
3181
|
+
* const gapUp = open.gt(high.offset(1));
|
|
3182
|
+
* plotchar(gapUp, "Gap up", { char: "▲", location: location.abovebar, color: color.teal });
|
|
3183
|
+
* ```
|
|
3184
|
+
*/
|
|
2327
3185
|
export function plotchar(condition: Series, title?: string, options: PlotCharOptions = {}): void {
|
|
3186
|
+
checkOptions('plotchar', options, [...SHAPE_OPTION_KEYS.filter((k) => k !== 'style'), 'char'], ['color', 'textcolor']);
|
|
2328
3187
|
emitMarkers('char', condition, title, options);
|
|
2329
3188
|
}
|
|
2330
3189
|
|
|
2331
3190
|
export interface PlotArrowOptions {
|
|
2332
|
-
/**
|
|
3191
|
+
/** Colour of the up arrows: one colour or one per bar. Default: #00FF00. */
|
|
2333
3192
|
colorup?: string | Array<string | undefined>;
|
|
2334
|
-
/**
|
|
3193
|
+
/** Colour of the down arrows: one colour or one per bar. Default: #FF0000. */
|
|
2335
3194
|
colordown?: string | Array<string | undefined>;
|
|
2336
|
-
/**
|
|
3195
|
+
/** Moves the arrows by this many bars (the arrow of bar i is drawn on bar i + offset). Default: 0. */
|
|
2337
3196
|
offset?: number;
|
|
2338
|
-
/**
|
|
3197
|
+
/** Height of the smallest arrow, in pixels. Default: 5. */
|
|
2339
3198
|
minheight?: number;
|
|
2340
|
-
/**
|
|
3199
|
+
/** Height of the largest arrow, in pixels. Default: 100. */
|
|
2341
3200
|
maxheight?: number;
|
|
3201
|
+
/** Where the arrows are shown: `display.all`, `display.none`... Default: everywhere. */
|
|
2342
3202
|
display?: ArrowConfig['display'];
|
|
2343
3203
|
/** Draw on the main chart pane even when the script is not an overlay (PineScript `force_overlay`); default false. */
|
|
2344
3204
|
force_overlay?: boolean;
|
|
@@ -2347,9 +3207,16 @@ export interface PlotArrowOptions {
|
|
|
2347
3207
|
}
|
|
2348
3208
|
|
|
2349
3209
|
/**
|
|
2350
|
-
*
|
|
2351
|
-
*
|
|
2352
|
-
*
|
|
3210
|
+
* Draws an up arrow below the bar where the value is positive and a down arrow above it where it is negative;
|
|
3211
|
+
* nothing for 0 or na. The larger the value, the longer the arrow (between `minheight` and `maxheight`).
|
|
3212
|
+
* @param series - Series whose sign gives the arrow's direction and whose size gives its length.
|
|
3213
|
+
* @param title - Name of the arrows in the settings and the alerts. Default: "Arrows".
|
|
3214
|
+
* @param options - Colours, heights, offset, display. Default: `{}` (green up, red down).
|
|
3215
|
+
* @example
|
|
3216
|
+
* ```js
|
|
3217
|
+
* const change = close.sub(close.offset(1));
|
|
3218
|
+
* plotarrow(change, "Change", { colorup: color.teal, colordown: color.orange });
|
|
3219
|
+
* ```
|
|
2353
3220
|
*/
|
|
2354
3221
|
export function plotarrow(series: Series, title?: string, options: PlotArrowOptions = {}): void {
|
|
2355
3222
|
if (intrabarRun) return; // dropped: an intrabar run's outputs aren't read
|
|
@@ -2424,21 +3291,41 @@ function emitBarColors(
|
|
|
2424
3291
|
}
|
|
2425
3292
|
|
|
2426
3293
|
/**
|
|
2427
|
-
*
|
|
2428
|
-
*
|
|
3294
|
+
* Colours the background of the script's pane behind each bar.
|
|
3295
|
+
* @param colors - One colour for every bar, or one per bar from `color.when()` (no colour on an na entry).
|
|
3296
|
+
* @param options - `offset` (bars to move the colours by), `title` (default "Background Color"), `force_overlay`
|
|
3297
|
+
* (true: colour the price chart's pane), `editable`. Default: `{}`.
|
|
3298
|
+
* @example
|
|
3299
|
+
* ```js
|
|
3300
|
+
* const rsi = ta.rsi(close, 14);
|
|
3301
|
+
* bgcolor(color.when(rsi.gt(70), color.new(color.red, 85)));
|
|
3302
|
+
* ```
|
|
2429
3303
|
*/
|
|
2430
3304
|
export function bgcolor(
|
|
2431
3305
|
colors: string | Array<string | undefined>,
|
|
2432
3306
|
options: { offset?: number; title?: string; force_overlay?: boolean; editable?: boolean } = {}
|
|
2433
3307
|
): void {
|
|
3308
|
+
if (ctx?.strict) checkColor('bgcolor(): the colour', colors);
|
|
3309
|
+
checkOptions('bgcolor', options, ['offset', 'title', 'force_overlay', 'editable']);
|
|
2434
3310
|
emitBarColors('bgcolor', colors, options);
|
|
2435
3311
|
}
|
|
2436
3312
|
|
|
2437
|
-
/**
|
|
3313
|
+
/**
|
|
3314
|
+
* Colours the chart's candles or bars, replacing their usual colours.
|
|
3315
|
+
* @param colors - One colour for every bar, or one per bar from `color.when()` (usual colour on an na entry).
|
|
3316
|
+
* @param options - `title` (default "Bar Color") and `editable`. Default: `{}`.
|
|
3317
|
+
* @example
|
|
3318
|
+
* ```js
|
|
3319
|
+
* const trendUp = close.gt(ta.sma(close, 50));
|
|
3320
|
+
* barcolor(color.when(trendUp, color.green, color.red));
|
|
3321
|
+
* ```
|
|
3322
|
+
*/
|
|
2438
3323
|
export function barcolor(
|
|
2439
3324
|
colors: string | Array<string | undefined>,
|
|
2440
3325
|
options: { title?: string; editable?: boolean } = {}
|
|
2441
3326
|
): void {
|
|
3327
|
+
if (ctx?.strict) checkColor('barcolor(): the colour', colors);
|
|
3328
|
+
checkOptions('barcolor', options, ['title', 'editable']);
|
|
2442
3329
|
emitBarColors('barcolor', colors, options);
|
|
2443
3330
|
}
|
|
2444
3331
|
|
|
@@ -2446,12 +3333,13 @@ export function barcolor(
|
|
|
2446
3333
|
export type ScriptCandleColor = string | Array<string | null | undefined>;
|
|
2447
3334
|
|
|
2448
3335
|
export interface PlotCandleOptions {
|
|
2449
|
-
/** Body colour:
|
|
3336
|
+
/** Body colour: one colour or one per bar (`color.when()`); an na entry gives a see-through body. Default: #2962FF. */
|
|
2450
3337
|
color?: ScriptCandleColor;
|
|
2451
|
-
/** Wick colour:
|
|
3338
|
+
/** Wick colour: one colour or one per bar. Default: #737375. */
|
|
2452
3339
|
wickcolor?: ScriptCandleColor;
|
|
2453
|
-
/** Border colour:
|
|
3340
|
+
/** Border colour: one colour or one per bar. Default: #000000. */
|
|
2454
3341
|
bordercolor?: ScriptCandleColor;
|
|
3342
|
+
/** Where the candles are shown: `display.all`, `display.none`... Default: everywhere. */
|
|
2455
3343
|
display?: CandleConfig['display'];
|
|
2456
3344
|
/** Draw on the main chart pane even when the script is not an overlay (PineScript `force_overlay`); default false. */
|
|
2457
3345
|
force_overlay?: boolean;
|
|
@@ -2460,8 +3348,9 @@ export interface PlotCandleOptions {
|
|
|
2460
3348
|
}
|
|
2461
3349
|
|
|
2462
3350
|
export interface PlotBarOptions {
|
|
2463
|
-
/** Bar colour:
|
|
3351
|
+
/** Bar colour: one colour or one per bar (`color.when()`); an na entry gives a see-through bar. Default: #2962FF. */
|
|
2464
3352
|
color?: ScriptCandleColor;
|
|
3353
|
+
/** Where the bars are shown: `display.all`, `display.none`... Default: everywhere. */
|
|
2465
3354
|
display?: CandleConfig['display'];
|
|
2466
3355
|
/** Draw on the main chart pane even when the script is not an overlay (PineScript `force_overlay`); default false. */
|
|
2467
3356
|
force_overlay?: boolean;
|
|
@@ -2503,7 +3392,14 @@ const staticColor = (col: ScriptCandleColor | undefined): string | undefined =>
|
|
|
2503
3392
|
* Colours of a plotcandle / plotbar argument left out, as the PineScript compiler declares them and the chart draws
|
|
2504
3393
|
* them (reference: body / bar #2962FF, wick #737375, border #000000; the wick and border do not follow the body).
|
|
2505
3394
|
*/
|
|
2506
|
-
export const DEFAULT_CANDLE_COLORS = {
|
|
3395
|
+
export const DEFAULT_CANDLE_COLORS = {
|
|
3396
|
+
/** Body colour (and the colour of `plotbar()` bars). */
|
|
3397
|
+
color: '#2962FF',
|
|
3398
|
+
/** Wick colour. */
|
|
3399
|
+
wickColor: '#737375',
|
|
3400
|
+
/** Border colour. */
|
|
3401
|
+
borderColor: '#000000',
|
|
3402
|
+
} as const;
|
|
2507
3403
|
|
|
2508
3404
|
/** The palettes of the per-bar colour arguments of a plotcandle / plotbar that have one. */
|
|
2509
3405
|
function candlePalettes(cols: { color?: ScriptCandleColor; wickColor?: ScriptCandleColor; borderColor?: ScriptCandleColor }): { palettes?: CandleConfig['palettes'] } {
|
|
@@ -2519,8 +3415,19 @@ function candlePalettes(cols: { color?: ScriptCandleColor; wickColor?: ScriptCan
|
|
|
2519
3415
|
const orDefault = (col: ScriptCandleColor | undefined, fallback: string): ScriptCandleColor => (col === undefined ? fallback : col);
|
|
2520
3416
|
|
|
2521
3417
|
/**
|
|
2522
|
-
*
|
|
2523
|
-
*
|
|
3418
|
+
* Draws candles from four Series (for example the candles of another symbol, or smoothed prices). A bar where one of
|
|
3419
|
+
* the four values is na has no candle.
|
|
3420
|
+
* @param open - Open of each candle.
|
|
3421
|
+
* @param high - High of each candle.
|
|
3422
|
+
* @param low - Low of each candle.
|
|
3423
|
+
* @param close - Close of each candle.
|
|
3424
|
+
* @param title - Name of the candles in the settings. Default: "PlotCandle".
|
|
3425
|
+
* @param options - Body, wick and border colours, display, force_overlay, editable. Default: `{}`.
|
|
3426
|
+
* @example
|
|
3427
|
+
* ```js
|
|
3428
|
+
* const o = ta.ema(open, 5), h = ta.ema(high, 5), l = ta.ema(low, 5), c = ta.ema(close, 5);
|
|
3429
|
+
* plotcandle(o, h, l, c, "Smoothed", { color: color.when(c.gt(o), color.teal, color.red) });
|
|
3430
|
+
* ```
|
|
2524
3431
|
*/
|
|
2525
3432
|
export function plotcandle(
|
|
2526
3433
|
open: Series,
|
|
@@ -2565,8 +3472,17 @@ export function plotcandle(
|
|
|
2565
3472
|
}
|
|
2566
3473
|
|
|
2567
3474
|
/**
|
|
2568
|
-
*
|
|
2569
|
-
*
|
|
3475
|
+
* Draws open-high-low-close bars from four Series. A bar where one of the four values is na is not drawn.
|
|
3476
|
+
* @param open - Open of each bar.
|
|
3477
|
+
* @param high - High of each bar.
|
|
3478
|
+
* @param low - Low of each bar.
|
|
3479
|
+
* @param close - Close of each bar.
|
|
3480
|
+
* @param title - Name of the bars in the settings. Default: "PlotBar".
|
|
3481
|
+
* @param options - Colour, display, force_overlay, editable. Default: `{}`.
|
|
3482
|
+
* @example
|
|
3483
|
+
* ```js
|
|
3484
|
+
* plotbar(open, high, low, close, "Bars", { color: color.when(close.gt(open), color.green, color.red) });
|
|
3485
|
+
* ```
|
|
2570
3486
|
*/
|
|
2571
3487
|
export function plotbar(
|
|
2572
3488
|
open: Series,
|
|
@@ -2676,6 +3592,20 @@ function outerWritesOf(fn: (...args: never[]) => unknown): string[] {
|
|
|
2676
3592
|
return found;
|
|
2677
3593
|
}
|
|
2678
3594
|
|
|
3595
|
+
/**
|
|
3596
|
+
* Runs a function on every bar, oldest first, for logic that needs the bar's values one at a time (state, ifs,
|
|
3597
|
+
* loops). The function reads the bar through `c` (`c.close`, `c.get(series)`, `c.get(series, 1)` for one bar back)
|
|
3598
|
+
* and returns the bar's value of the Series that `eachBar` gives back (na when it returns nothing).
|
|
3599
|
+
* @param fn - Called once per bar with the bar's context; returns a number (or true / false) for that bar.
|
|
3600
|
+
* @returns Series of the values the function returned.
|
|
3601
|
+
* @example
|
|
3602
|
+
* ```js
|
|
3603
|
+
* const fast = ta.sma(close, 10);
|
|
3604
|
+
* let count = 0;
|
|
3605
|
+
* const streak = eachBar((c) => (count = c.get(close) > c.get(fast) ? count + 1 : 0));
|
|
3606
|
+
* plot(streak, "Bars above");
|
|
3607
|
+
* ```
|
|
3608
|
+
*/
|
|
2679
3609
|
export function eachBar(fn: (c: BarContext) => number | boolean | void): Series {
|
|
2680
3610
|
return runBlock(fn);
|
|
2681
3611
|
}
|
|
@@ -3156,10 +4086,12 @@ for (const name of [...STRATEGY_NUMBER_VARIABLES, ...STRATEGY_TEXT_VARIABLES]) {
|
|
|
3156
4086
|
* });
|
|
3157
4087
|
* ```
|
|
3158
4088
|
*/
|
|
3159
|
-
export const strategy = Object.defineProperties(
|
|
4089
|
+
export const strategy: StrategyNamespace = Object.defineProperties(
|
|
3160
4090
|
Object.assign((title: string, options?: StrategyOptions) => declareStrategy(title, options), strategyMembers),
|
|
3161
4091
|
variableGetters
|
|
3162
4092
|
) as StrategyApi;
|
|
4093
|
+
sameKeys<StrategyApi, StrategyNamespace>(true);
|
|
4094
|
+
sameKeys<StrategyApi['risk'], StrategyNamespace['risk']>(true);
|
|
3163
4095
|
|
|
3164
4096
|
/** Types of chart PineScript tells apart (`chart.is_*`); every other type is 'standard'. */
|
|
3165
4097
|
export type ChartType = 'standard' | 'heikinashi' | 'renko' | 'kagi' | 'linebreak' | 'pnf' | 'range';
|
|
@@ -3231,6 +4163,8 @@ export interface ChartContext {
|
|
|
3231
4163
|
ticker?: string;
|
|
3232
4164
|
/** The chart's own symbol (PineScript `syminfo.main_tickerid`, the same inside `request.security`); default `tickerid` */
|
|
3233
4165
|
mainTickerid?: string;
|
|
4166
|
+
/** The chart's own timeframe (`timeframe.main_period`, the same inside `request.security`); default `timeframe` */
|
|
4167
|
+
mainTimeframe?: string;
|
|
3234
4168
|
/** Two-letter code of the country the symbol trades in (PineScript `syminfo.country`): "US", "IN" */
|
|
3235
4169
|
country?: string | null;
|
|
3236
4170
|
/** Contract a continuous future stands for (PineScript `syminfo.current_contract`): "ESZ2026" for CME_MINI:ES1! */
|
|
@@ -3465,13 +4399,14 @@ function exchangeTimezone(): string {
|
|
|
3465
4399
|
* PineScript `timeframe.*`: the chart timeframe variables (from the chart context), and
|
|
3466
4400
|
* `in_seconds(timeframe?)`, `from_seconds(seconds)`.
|
|
3467
4401
|
*/
|
|
3468
|
-
export const timeframe = {
|
|
4402
|
+
export const timeframe: TimeframeNamespace = {
|
|
3469
4403
|
...timeframeCore,
|
|
3470
4404
|
get period(): string {
|
|
3471
4405
|
return chartTimeframe().period;
|
|
3472
4406
|
},
|
|
3473
4407
|
get main_period(): string {
|
|
3474
|
-
|
|
4408
|
+
const main = chartCtx.mainTimeframe;
|
|
4409
|
+
return main ? timeframeCore.info(main).period : chartTimeframe().period;
|
|
3475
4410
|
},
|
|
3476
4411
|
get multiplier(): number {
|
|
3477
4412
|
return chartTimeframe().multiplier;
|
|
@@ -3630,7 +4565,7 @@ function symbolScale(): [number, number] {
|
|
|
3630
4565
|
* PineScript `syminfo.*`, from the chart context (inside `request.security`, the requested symbol's). A field the
|
|
3631
4566
|
* symbol has none of is na ("" for a text); a field the host did not give throws.
|
|
3632
4567
|
*/
|
|
3633
|
-
export const syminfo = {
|
|
4568
|
+
export const syminfo: SyminfoNamespace = {
|
|
3634
4569
|
get mintick(): number {
|
|
3635
4570
|
return symbolProperty('mintick');
|
|
3636
4571
|
},
|
|
@@ -3760,7 +4695,17 @@ export const syminfo = {
|
|
|
3760
4695
|
|
|
3761
4696
|
/** A calendar function: `(time, timezone?)` on a UNIX time or on a Series of times. */
|
|
3762
4697
|
interface CalendarFunction {
|
|
4698
|
+
/**
|
|
4699
|
+
* @param time - A time in UNIX milliseconds.
|
|
4700
|
+
* @param timezone - Time zone to read the time in: "America/New_York", "UTC+2"... Default: the exchange's.
|
|
4701
|
+
* @returns The calendar field of that time.
|
|
4702
|
+
*/
|
|
3763
4703
|
(time: number, timezone?: string): number;
|
|
4704
|
+
/**
|
|
4705
|
+
* @param time - A Series of times in UNIX milliseconds, e.g. `time`.
|
|
4706
|
+
* @param timezone - Time zone to read the times in: "America/New_York", "UTC+2"... Default: the exchange's.
|
|
4707
|
+
* @returns Series of the calendar field of each time.
|
|
4708
|
+
*/
|
|
3764
4709
|
(time: Series, timezone?: string): Series;
|
|
3765
4710
|
}
|
|
3766
4711
|
|
|
@@ -3771,29 +4716,103 @@ function calendar(fn: (time: number, timezone: string) => number): CalendarFunct
|
|
|
3771
4716
|
}) as CalendarFunction;
|
|
3772
4717
|
}
|
|
3773
4718
|
|
|
3774
|
-
/**
|
|
3775
|
-
|
|
3776
|
-
|
|
3777
|
-
|
|
3778
|
-
|
|
3779
|
-
|
|
3780
|
-
|
|
3781
|
-
|
|
3782
|
-
|
|
3783
|
-
/**
|
|
3784
|
-
|
|
3785
|
-
|
|
3786
|
-
|
|
3787
|
-
|
|
3788
|
-
|
|
3789
|
-
|
|
3790
|
-
|
|
4719
|
+
/**
|
|
4720
|
+
* The year of a time (2025...). Works on one time or on a Series of times (`year(time)` gives the value of each bar).
|
|
4721
|
+
* @example
|
|
4722
|
+
* ```js
|
|
4723
|
+
* const newYear = year(time).neq(year(time).offset(1));
|
|
4724
|
+
* bgcolor(color.when(newYear, color.new(color.blue, 80)));
|
|
4725
|
+
* ```
|
|
4726
|
+
*/
|
|
4727
|
+
export const year: CalendarFunction = calendar(timeCore.year);
|
|
4728
|
+
/**
|
|
4729
|
+
* 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).
|
|
4730
|
+
* @example
|
|
4731
|
+
* ```js
|
|
4732
|
+
* const january = month(time).eq(1);
|
|
4733
|
+
* bgcolor(color.when(january, color.new(color.teal, 85)));
|
|
4734
|
+
* ```
|
|
4735
|
+
*/
|
|
4736
|
+
export const month: CalendarFunction = calendar(timeCore.month);
|
|
4737
|
+
/**
|
|
4738
|
+
* 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).
|
|
4739
|
+
* @example
|
|
4740
|
+
* ```js
|
|
4741
|
+
* plot(weekofyear(time), "Week");
|
|
4742
|
+
* ```
|
|
4743
|
+
*/
|
|
4744
|
+
export const weekofyear: CalendarFunction = calendar(timeCore.weekofyear);
|
|
4745
|
+
/**
|
|
4746
|
+
* 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).
|
|
4747
|
+
* @example
|
|
4748
|
+
* ```js
|
|
4749
|
+
* plot(dayofmonth(time, "UTC"), "Day of month");
|
|
4750
|
+
* ```
|
|
4751
|
+
*/
|
|
4752
|
+
export const dayofmonth: CalendarFunction = calendar(timeCore.dayofmonth);
|
|
4753
|
+
/**
|
|
4754
|
+
* 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
|
|
4755
|
+
* `dayofweek.monday`... constants.
|
|
4756
|
+
* @example
|
|
4757
|
+
* ```js
|
|
4758
|
+
* const monday = dayofweek(time).eq(dayofweek.monday);
|
|
4759
|
+
* bgcolor(color.when(monday, color.new(color.gray, 90)));
|
|
4760
|
+
* ```
|
|
4761
|
+
*/
|
|
4762
|
+
export const dayofweek: CalendarFunction & typeof pineConstants.daysOfWeek = Object.assign(calendar(timeCore.dayofweek), pineConstants.daysOfWeek);
|
|
4763
|
+
/**
|
|
4764
|
+
* 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).
|
|
4765
|
+
* @example
|
|
4766
|
+
* ```js
|
|
4767
|
+
* const morning = hour(time).lt(12);
|
|
4768
|
+
* bgcolor(color.when(morning, color.new(color.orange, 90)));
|
|
4769
|
+
* ```
|
|
4770
|
+
*/
|
|
4771
|
+
export const hour: CalendarFunction = calendar(timeCore.hour);
|
|
4772
|
+
/**
|
|
4773
|
+
* 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).
|
|
4774
|
+
* @example
|
|
4775
|
+
* ```js
|
|
4776
|
+
* plot(minute(time), "Minute");
|
|
4777
|
+
* ```
|
|
4778
|
+
*/
|
|
4779
|
+
export const minute: CalendarFunction = calendar(timeCore.minute);
|
|
4780
|
+
/**
|
|
4781
|
+
* 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).
|
|
4782
|
+
* @example
|
|
4783
|
+
* ```js
|
|
4784
|
+
* plot(second(time), "Second");
|
|
4785
|
+
* ```
|
|
4786
|
+
*/
|
|
4787
|
+
export const second: CalendarFunction = calendar(timeCore.second);
|
|
3791
4788
|
|
|
3792
4789
|
/**
|
|
3793
|
-
*
|
|
3794
|
-
*
|
|
4790
|
+
* The UNIX time (milliseconds) of a date written as text.
|
|
4791
|
+
* @param dateString - A date such as "2024-03-15", "2024-03-15T09:30" or "15 Mar 2024 09:30 GMT+1"; without a time
|
|
4792
|
+
* zone it is UTC.
|
|
4793
|
+
* @returns The time in UNIX milliseconds.
|
|
4794
|
+
* @example
|
|
4795
|
+
* ```js
|
|
4796
|
+
* const start = timestamp("2024-01-01");
|
|
4797
|
+
* bgcolor(color.when(time.gte(start), color.new(color.green, 92)));
|
|
4798
|
+
* ```
|
|
3795
4799
|
*/
|
|
3796
4800
|
export function timestamp(dateString: string): number;
|
|
4801
|
+
/**
|
|
4802
|
+
* The UNIX time (milliseconds) of a date and time in a time zone.
|
|
4803
|
+
* @param timezone - Time zone: "America/New_York", "UTC+2"...
|
|
4804
|
+
* @param year - Year, e.g. 2024.
|
|
4805
|
+
* @param month - Month, 1 to 12.
|
|
4806
|
+
* @param day - Day of the month, 1 to 31.
|
|
4807
|
+
* @param hour - Hour, 0 to 23. Default: 0.
|
|
4808
|
+
* @param minute - Minute. Default: 0.
|
|
4809
|
+
* @param second - Second. Default: 0.
|
|
4810
|
+
* @returns The time in UNIX milliseconds.
|
|
4811
|
+
* @example
|
|
4812
|
+
* ```js
|
|
4813
|
+
* const open = timestamp("America/New_York", 2024, 3, 15, 9, 30);
|
|
4814
|
+
* ```
|
|
4815
|
+
*/
|
|
3797
4816
|
export function timestamp(
|
|
3798
4817
|
timezone: string,
|
|
3799
4818
|
year: number,
|
|
@@ -3803,6 +4822,21 @@ export function timestamp(
|
|
|
3803
4822
|
minute?: number,
|
|
3804
4823
|
second?: number
|
|
3805
4824
|
): number;
|
|
4825
|
+
/**
|
|
4826
|
+
* The UNIX time (milliseconds) of a date and time in the exchange's time zone.
|
|
4827
|
+
* @param year - Year, e.g. 2024.
|
|
4828
|
+
* @param month - Month, 1 to 12.
|
|
4829
|
+
* @param day - Day of the month, 1 to 31.
|
|
4830
|
+
* @param hour - Hour, 0 to 23. Default: 0.
|
|
4831
|
+
* @param minute - Minute. Default: 0.
|
|
4832
|
+
* @param second - Second. Default: 0.
|
|
4833
|
+
* @returns The time in UNIX milliseconds.
|
|
4834
|
+
* @example
|
|
4835
|
+
* ```js
|
|
4836
|
+
* const from = timestamp(2024, 1, 1);
|
|
4837
|
+
* plotshape(time.eq(from), "Start");
|
|
4838
|
+
* ```
|
|
4839
|
+
*/
|
|
3806
4840
|
export function timestamp(year: number, month: number, day: number, hour?: number, minute?: number, second?: number): number;
|
|
3807
4841
|
export function timestamp(first: string | number, ...rest: Array<number | undefined>): number {
|
|
3808
4842
|
if (typeof first === 'number') {
|
|
@@ -3814,25 +4848,44 @@ export function timestamp(first: string | number, ...rest: Array<number | undefi
|
|
|
3814
4848
|
return timeCore.timestamp(first, y, m, d, h, mi, s);
|
|
3815
4849
|
}
|
|
3816
4850
|
|
|
3817
|
-
/**
|
|
4851
|
+
/**
|
|
4852
|
+
* Whether a time is inside a session (trading hours).
|
|
4853
|
+
* @param time - A time in UNIX milliseconds, e.g. `c.time` in `eachBar()`.
|
|
4854
|
+
* @param session - Session hours and days: "0930-1600", "0930-1600:23456" (Monday to Friday), "1800-0500" (overnight).
|
|
4855
|
+
* @param timezone - Time zone of the session hours. Default: the exchange's.
|
|
4856
|
+
* @returns true when the time is in the session.
|
|
4857
|
+
* @example
|
|
4858
|
+
* ```js
|
|
4859
|
+
* const regular = eachBar((c) => inSession(c.time, "0930-1600"));
|
|
4860
|
+
* bgcolor(color.when(regular, color.new(color.blue, 92)));
|
|
4861
|
+
* ```
|
|
4862
|
+
*/
|
|
3818
4863
|
export function inSession(time: number, session: string, timezone?: string): boolean {
|
|
3819
4864
|
return timeCore.inSession(time, session, timezone ?? exchangeTimezone());
|
|
3820
4865
|
}
|
|
3821
4866
|
|
|
3822
|
-
/**
|
|
3823
|
-
|
|
4867
|
+
/**
|
|
4868
|
+
* Text functions: `str.tostring` (a number as text), `str.format` (a pattern with values), `str.format_time` (a date),
|
|
4869
|
+
* search, replace, split, case... `str.format_time` and the dates of `str.format` use the exchange's time zone by
|
|
4870
|
+
* default.
|
|
4871
|
+
* @example
|
|
4872
|
+
* ```js
|
|
4873
|
+
* eachBar((c) => {
|
|
4874
|
+
* if (barstate.islast) log.info(str.format("Close {0} at {1}", c.get(close), str.format_time(c.get(time), "HH:mm")));
|
|
4875
|
+
* });
|
|
4876
|
+
* ```
|
|
4877
|
+
*/
|
|
4878
|
+
export const str: typeof strCore = strictNamespace('str', {
|
|
3824
4879
|
...strCore,
|
|
3825
4880
|
// format.mintick uses the chart symbol's tick and price scale (syminfo.mintick, syminfo.pricescale)
|
|
3826
4881
|
tostring: ((value: unknown, format?: string, mintick?: number, pricescale?: number) =>
|
|
3827
4882
|
format === 'mintick' && mintick === undefined
|
|
3828
4883
|
? strCore.tostring(value as never, format, syminfo.mintick, pricescale ?? syminfo.pricescale)
|
|
3829
4884
|
: strCore.tostring(value as never, format, mintick, pricescale)) as typeof strCore.tostring,
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
|
|
3833
|
-
format(pattern: string, ...args: unknown[]): string
|
|
3834
|
-
return formatMessage(pattern, args, exchangeTimezone);
|
|
3835
|
-
},
|
|
4885
|
+
// the exchange time zone by default; the documentation is the library function's
|
|
4886
|
+
format_time: ((time: number, format: string = "yyyy-MM-dd'T'HH:mm:ssZ", timezone?: string): string =>
|
|
4887
|
+
strCore.format_time(time, format, timezone ?? exchangeTimezone())) as typeof strCore.format_time,
|
|
4888
|
+
format: ((pattern: string, ...args: unknown[]): string => formatMessage(pattern, args, exchangeTimezone)) as typeof strCore.format,
|
|
3836
4889
|
});
|
|
3837
4890
|
|
|
3838
4891
|
// ── Session values (issue #100) ──────────────────────────────────────────────
|
|
@@ -3883,22 +4936,32 @@ function chartSessionPeriods(timeframeString: string, session?: string, timezone
|
|
|
3883
4936
|
return sessionPeriods(bars, { ...chartCtx, timezone: exchangeTimezone() }, timeframeString, session, timezone);
|
|
3884
4937
|
}
|
|
3885
4938
|
|
|
4939
|
+
/**
|
|
4940
|
+
* The open time of the period of `tf` that holds each bar, in UNIX milliseconds; na on bars outside `session`.
|
|
4941
|
+
* @param tf - Timeframe of the periods: "D", "W", "60"... Default: the chart's.
|
|
4942
|
+
* @param session - Session hours, e.g. "0930-1600"; bars outside it give na. Default: the symbol's.
|
|
4943
|
+
* @param timezone - Time zone of the session hours. Default: the exchange's.
|
|
4944
|
+
* @returns Series of period open times.
|
|
4945
|
+
*/
|
|
3886
4946
|
function timeFunction(tf?: string, session?: string, timezone?: string): Series {
|
|
3887
4947
|
collector();
|
|
3888
4948
|
const { open } = chartSessionPeriods(tf || chartTimeframe().period, session, timezone);
|
|
3889
4949
|
return perBar((t) => open(t));
|
|
3890
4950
|
}
|
|
3891
4951
|
|
|
4952
|
+
/**
|
|
4953
|
+
* The close time of the period of `tf` that holds each bar, in UNIX milliseconds; na on bars outside `session`.
|
|
4954
|
+
* @param tf - Timeframe of the periods: "D", "W", "60"... Default: the chart's.
|
|
4955
|
+
* @param session - Session hours, e.g. "0930-1600"; bars outside it give na. Default: the symbol's.
|
|
4956
|
+
* @param timezone - Time zone of the session hours. Default: the exchange's.
|
|
4957
|
+
* @returns Series of period close times.
|
|
4958
|
+
*/
|
|
3892
4959
|
function timeCloseFunction(tf?: string, session?: string, timezone?: string): Series {
|
|
3893
4960
|
collector();
|
|
3894
4961
|
const { close } = chartSessionPeriods(tf || chartTimeframe().period, session, timezone);
|
|
3895
4962
|
return perBar((t) => close(t));
|
|
3896
4963
|
}
|
|
3897
4964
|
|
|
3898
|
-
/**
|
|
3899
|
-
* PineScript `time`: the bar open time in ms (a Series), and `time(timeframe?, session?, timezone?)`:
|
|
3900
|
-
* the open time of the `timeframe` period that contains the bar, `na` outside `session`.
|
|
3901
|
-
*/
|
|
3902
4965
|
/** Current time of the run in ms, see `ChartContext.now`. */
|
|
3903
4966
|
let runNow = NaN;
|
|
3904
4967
|
|
|
@@ -3908,11 +4971,24 @@ export const timenow = new Series(ctxBars, () => {
|
|
|
3908
4971
|
return runNow;
|
|
3909
4972
|
});
|
|
3910
4973
|
|
|
4974
|
+
/**
|
|
4975
|
+
* The open time of each bar, in UNIX milliseconds (a Series). Called as `time(tf?, session?, timezone?)`: the open
|
|
4976
|
+
* time of the `tf` period that holds the bar, na outside `session`.
|
|
4977
|
+
* @example
|
|
4978
|
+
* ```js
|
|
4979
|
+
* const newDay = time("D").neq(time("D").offset(1));
|
|
4980
|
+
* bgcolor(color.when(newDay, color.new(color.gray, 85)));
|
|
4981
|
+
* ```
|
|
4982
|
+
*/
|
|
3911
4983
|
export const time = callableSeries(new Series(ctxBars, (b) => barTime(b)), timeFunction);
|
|
3912
4984
|
|
|
3913
4985
|
/**
|
|
3914
|
-
*
|
|
3915
|
-
*
|
|
4986
|
+
* The close time of each bar, in UNIX milliseconds (a Series). Called as `time_close(tf?, session?, timezone?)`: the
|
|
4987
|
+
* close time of the `tf` period that holds the bar, na outside `session`.
|
|
4988
|
+
* @example
|
|
4989
|
+
* ```js
|
|
4990
|
+
* plot(time_close.sub(time).div(60000), "Bar minutes");
|
|
4991
|
+
* ```
|
|
3916
4992
|
*/
|
|
3917
4993
|
export const time_close = callableSeries(
|
|
3918
4994
|
new Series(ctxBars, (_b, i) => sessionBars().bars.closeOf(barTime(ctxBars.bars[i]!), chartTimeframe().period)),
|
|
@@ -3994,7 +5070,7 @@ const lastRealtime = (i: number, n: number): boolean => i === n - 1 && chartCtx.
|
|
|
3994
5070
|
* it is a history bar, as in PineScript.
|
|
3995
5071
|
* `islastconfirmedhistory` is the last bar when it is confirmed and not realtime, else the bar before it.
|
|
3996
5072
|
*/
|
|
3997
|
-
export const barstate = {
|
|
5073
|
+
export const barstate: BarstateNamespace = {
|
|
3998
5074
|
get isfirst(): Series { return namedFlag('isfirst', (i) => i === 0); },
|
|
3999
5075
|
get islast(): Series { return namedFlag('islast', (i, n) => i === chartBarCount(n) - 1); },
|
|
4000
5076
|
get isconfirmed(): Series { return namedFlag('isconfirmed', (i, n) => i < n - 1 || chartCtx.lastBarConfirmed === true); },
|
|
@@ -4017,7 +5093,7 @@ export const barstate = {
|
|
|
4017
5093
|
* PineScript `session.*` (1 / 0 per bar) and the constants `session.regular` / `session.extended`.
|
|
4018
5094
|
* First and last bars are per session period; market / pre / post market use the regular hours.
|
|
4019
5095
|
*/
|
|
4020
|
-
export const session = {
|
|
5096
|
+
export const session: SessionNamespace = {
|
|
4021
5097
|
regular: 'regular',
|
|
4022
5098
|
extended: 'extended',
|
|
4023
5099
|
get isfirstbar(): Series { return flag('isfirstbar'); },
|
|
@@ -4032,7 +5108,7 @@ export const session = {
|
|
|
4032
5108
|
// ── request.security (issue #101) ─────────────────────────────────────────────
|
|
4033
5109
|
|
|
4034
5110
|
/** PineScript `barmerge.*` constants of `request.security`. */
|
|
4035
|
-
export const barmerge = {
|
|
5111
|
+
export const barmerge: BarmergeNamespace = {
|
|
4036
5112
|
gaps_on: 'gaps_on',
|
|
4037
5113
|
gaps_off: 'gaps_off',
|
|
4038
5114
|
lookahead_on: 'lookahead_on',
|
|
@@ -4042,7 +5118,7 @@ export const barmerge = {
|
|
|
4042
5118
|
const HEIKIN_ASHI = 'heikinashi:';
|
|
4043
5119
|
|
|
4044
5120
|
/** PineScript `ticker.heikinashi(symbol)` / `ticker.standard(symbol)` for the chart symbol. */
|
|
4045
|
-
export const ticker = {
|
|
5121
|
+
export const ticker: TickerNamespace = {
|
|
4046
5122
|
heikinashi(symbol: string): string {
|
|
4047
5123
|
return HEIKIN_ASHI + symbol;
|
|
4048
5124
|
},
|
|
@@ -4097,8 +5173,9 @@ function security<T extends SecurityValue>(
|
|
|
4097
5173
|
if (base !== '' && base !== chartCtx.tickerid) {
|
|
4098
5174
|
return externalSecurity(base, heikin, tf, expression, gaps, lookahead, ignore_invalid_symbol, false);
|
|
4099
5175
|
}
|
|
4100
|
-
|
|
4101
|
-
|
|
5176
|
+
const ticks = timeframeCore.info(tf).isticks && tf !== chart.period;
|
|
5177
|
+
if (ticks || timeframeCore.in_seconds(tf) < timeframeCore.in_seconds(chart.period)) {
|
|
5178
|
+
// a lower timeframe of the chart symbol, or its ticks: its bars come from ChartContext.bars (#181, #214)
|
|
4102
5179
|
return externalSecurity(chartCtx.tickerid ?? '', heikin, tf, expression, gaps, lookahead, ignore_invalid_symbol, true);
|
|
4103
5180
|
}
|
|
4104
5181
|
|
|
@@ -4137,7 +5214,7 @@ function security<T extends SecurityValue>(
|
|
|
4137
5214
|
let result: T;
|
|
4138
5215
|
let values: number[][];
|
|
4139
5216
|
ctxBars.setAll(htf);
|
|
4140
|
-
chartCtx = { ...chartCtx, timeframe: tf };
|
|
5217
|
+
chartCtx = { ...chartCtx, timeframe: tf, mainTimeframe: chartCtx.mainTimeframe ?? chartCtx.timeframe };
|
|
4141
5218
|
try {
|
|
4142
5219
|
result = expression();
|
|
4143
5220
|
const parts = Array.isArray(result) ? result : [result];
|
|
@@ -4189,7 +5266,13 @@ function runExternal<T extends SecurityValue>(
|
|
|
4189
5266
|
ctxBars.setAll(bars);
|
|
4190
5267
|
// the expression sees that symbol: its ticker, timeframe, calendar and properties (the chart's own symbol stays the
|
|
4191
5268
|
// main one)
|
|
4192
|
-
const seen: ChartContext = {
|
|
5269
|
+
const seen: ChartContext = {
|
|
5270
|
+
...chartCtx,
|
|
5271
|
+
tickerid: symbol,
|
|
5272
|
+
timeframe: tf,
|
|
5273
|
+
mainTickerid: chartCtx.mainTickerid ?? chartCtx.tickerid,
|
|
5274
|
+
mainTimeframe: chartCtx.mainTimeframe ?? chartCtx.timeframe,
|
|
5275
|
+
};
|
|
4193
5276
|
for (const key of SYMBOL_INFO_KEYS) (seen as Record<string, unknown>)[key] = info[key];
|
|
4194
5277
|
chartCtx = seen;
|
|
4195
5278
|
try {
|
|
@@ -4415,7 +5498,7 @@ function eventSeries(times: number[], values: number[], gaps: string | undefined
|
|
|
4415
5498
|
}
|
|
4416
5499
|
|
|
4417
5500
|
/** PineScript `dividends.*`: the fields of `request.dividends` and the next announced dividend of the chart symbol. */
|
|
4418
|
-
export const dividends = {
|
|
5501
|
+
export const dividends: DividendsNamespace = {
|
|
4419
5502
|
net: 'net',
|
|
4420
5503
|
gross: 'gross',
|
|
4421
5504
|
/** Amount of the next dividend (net), na when none is announced */
|
|
@@ -4433,10 +5516,10 @@ export const dividends = {
|
|
|
4433
5516
|
} as const;
|
|
4434
5517
|
|
|
4435
5518
|
/** PineScript `splits.*`: the fields of `request.splits`. */
|
|
4436
|
-
export const splits = { numerator: 'numerator', denominator: 'denominator' } as const;
|
|
5519
|
+
export const splits: SplitsNamespace = { numerator: 'numerator', denominator: 'denominator' } as const;
|
|
4437
5520
|
|
|
4438
5521
|
/** PineScript `earnings.*`: the fields of `request.earnings` and the next earnings release of the chart symbol. */
|
|
4439
|
-
export const earnings = {
|
|
5522
|
+
export const earnings: EarningsNamespace = {
|
|
4440
5523
|
actual: 'actual',
|
|
4441
5524
|
estimate: 'estimate',
|
|
4442
5525
|
standardized: 'standardized',
|
|
@@ -4536,7 +5619,7 @@ function earningsCall(...args: EventRequestCall): Series {
|
|
|
4536
5619
|
return eventSeries(list.map((e) => e.time), eventField(list, field, 'request.earnings', ticker), a[2] as string | undefined, a[3] as string | undefined);
|
|
4537
5620
|
}
|
|
4538
5621
|
|
|
4539
|
-
|
|
5622
|
+
const requestMembers = strictNamespace('request', {
|
|
4540
5623
|
security: securityCall,
|
|
4541
5624
|
security_lower_tf: securityLowerTfCall,
|
|
4542
5625
|
seed: seedCall,
|
|
@@ -4544,6 +5627,18 @@ export const request = strictNamespace('request', {
|
|
|
4544
5627
|
splits: splitsCall,
|
|
4545
5628
|
earnings: earningsCall,
|
|
4546
5629
|
});
|
|
5630
|
+
/**
|
|
5631
|
+
* Data from other symbols, timeframes and sources: `request.security` (another symbol or timeframe),
|
|
5632
|
+
* `request.security_lower_tf` (the lower-timeframe bars inside each bar), `request.seed` (a separately published data series),
|
|
5633
|
+
* dividends, splits and earnings. Call it before any `eachBar()` loop.
|
|
5634
|
+
* @example
|
|
5635
|
+
* ```js
|
|
5636
|
+
* const dailyClose = request.security("", "D", () => close);
|
|
5637
|
+
* plot(dailyClose, "Daily close");
|
|
5638
|
+
* ```
|
|
5639
|
+
*/
|
|
5640
|
+
export const request: RequestNamespace = requestMembers;
|
|
5641
|
+
sameKeys<typeof requestMembers, RequestNamespace>(true);
|
|
4547
5642
|
|
|
4548
5643
|
// ── Drawing objects ──────────────────────────────────────────────────────────
|
|
4549
5644
|
// The drawing namespaces come from this bundle so that they share the registry that
|
|
@@ -4674,21 +5769,42 @@ export interface LinefillNewArgs {
|
|
|
4674
5769
|
const loopBar = (): number => currentBar;
|
|
4675
5770
|
|
|
4676
5771
|
/** Wraps a drawing namespace and keeps its `all` getter (the live drawings in creation order). */
|
|
4677
|
-
|
|
5772
|
+
/** A drawing namespace of scripts: the members of `T`, and `all`. */
|
|
5773
|
+
type DrawingNamespace<T, D> = Omit<ScriptDrawing<T>, 'all'> & {
|
|
5774
|
+
/** The live drawings of this kind, oldest first (a new array on each read). */
|
|
5775
|
+
readonly all: D[];
|
|
5776
|
+
};
|
|
5777
|
+
|
|
5778
|
+
function drawings<T extends Record<string, unknown>, D>(name: string, members: T, all: () => D[]): DrawingNamespace<T, D> {
|
|
4678
5779
|
const out = drawingNamespace(name, members, loopBar) as ScriptDrawing<T>;
|
|
4679
|
-
return Object.defineProperty(out, 'all', { get: all, enumerable: true }) as
|
|
5780
|
+
return Object.defineProperty(out, 'all', { get: all, enumerable: true }) as DrawingNamespace<T, D>;
|
|
4680
5781
|
}
|
|
4681
5782
|
|
|
4682
|
-
|
|
4683
|
-
|
|
5783
|
+
// The members are typed by their modules, so that the editor shows each function's documentation.
|
|
5784
|
+
const lineNs: DrawingNamespace<typeof lineCore & typeof pineConstants.lineStyles, Line> = drawings(
|
|
5785
|
+
'line',
|
|
5786
|
+
{ ...lineCore, ...pineConstants.lineStyles },
|
|
5787
|
+
() => lineCore.all()
|
|
5788
|
+
);
|
|
5789
|
+
/**
|
|
5790
|
+
* Lines between two chart points: `line.new()` draws one, `line.set_*` / `line.get_*` move and read it, `line.style_*`
|
|
5791
|
+
* are its styles, `line.all` lists the live lines.
|
|
5792
|
+
*/
|
|
4684
5793
|
export const line = lineNs as typeof lineNs & {
|
|
4685
5794
|
new: ((args: LineNewArgs) => Line) &
|
|
4686
5795
|
((x1: Numeric, y1: Numeric, x2: Numeric, y2: Numeric, args: LineNewArgs) => Line) &
|
|
4687
5796
|
((first_point: ChartPoint, second_point: ChartPoint, args: LineNewArgs) => Line);
|
|
4688
5797
|
};
|
|
4689
5798
|
|
|
4690
|
-
const labelNs
|
|
4691
|
-
|
|
5799
|
+
const labelNs: DrawingNamespace<typeof labelCore & typeof pineConstants.labelStyles, Label> = drawings(
|
|
5800
|
+
'label',
|
|
5801
|
+
{ ...labelCore, ...pineConstants.labelStyles },
|
|
5802
|
+
() => labelCore.all()
|
|
5803
|
+
);
|
|
5804
|
+
/**
|
|
5805
|
+
* Text boxes and shapes at a chart point: `label.new()` draws one, `label.set_*` / `label.get_*` change and read it,
|
|
5806
|
+
* `label.style_*` are its styles, `label.all` lists the live labels.
|
|
5807
|
+
*/
|
|
4692
5808
|
export const label = labelNs as typeof labelNs & {
|
|
4693
5809
|
new: ((args: LabelNewArgs) => Label) &
|
|
4694
5810
|
((x: Numeric, y: Numeric, args: LabelNewArgs) => Label) &
|
|
@@ -4697,53 +5813,62 @@ export const label = labelNs as typeof labelNs & {
|
|
|
4697
5813
|
((point: ChartPoint, text: string, args: LabelNewArgs) => Label);
|
|
4698
5814
|
};
|
|
4699
5815
|
|
|
4700
|
-
const boxNs = drawings('box', { ...boxCore }, () => boxCore.all());
|
|
4701
|
-
/**
|
|
5816
|
+
const boxNs: DrawingNamespace<typeof boxCore, Box> = drawings('box', { ...boxCore }, () => boxCore.all());
|
|
5817
|
+
/**
|
|
5818
|
+
* Rectangles between two x coordinates and two prices, with optional text: `box.new()` draws one, `box.set_*` /
|
|
5819
|
+
* `box.get_*` change and read it, `box.all` lists the live boxes.
|
|
5820
|
+
*/
|
|
4702
5821
|
export const box = boxNs as typeof boxNs & {
|
|
4703
5822
|
new: ((args: BoxNewArgs) => Box) &
|
|
4704
5823
|
((left: Numeric, top: Numeric, right: Numeric, bottom: Numeric, args: BoxNewArgs) => Box) &
|
|
4705
5824
|
((top_left: ChartPoint, bottom_right: ChartPoint, args: BoxNewArgs) => Box);
|
|
4706
5825
|
};
|
|
4707
5826
|
|
|
4708
|
-
const linefillNs = drawings('linefill', { ...linefillCore }, () => linefillCore.all());
|
|
4709
|
-
/**
|
|
5827
|
+
const linefillNs: DrawingNamespace<typeof linefillCore, Linefill> = drawings('linefill', { ...linefillCore }, () => linefillCore.all());
|
|
5828
|
+
/**
|
|
5829
|
+
* Colour fills between two lines that follow the lines when they move: `linefill.new()`, `linefill.set_color()`,
|
|
5830
|
+
* `linefill.all`.
|
|
5831
|
+
*/
|
|
4710
5832
|
export const linefill = linefillNs as typeof linefillNs & {
|
|
4711
5833
|
new: ((args: LinefillNewArgs) => Linefill) & ((line1: Line, line2: Line, args: LinefillNewArgs) => Linefill);
|
|
4712
5834
|
};
|
|
4713
5835
|
|
|
4714
|
-
const polylineNs = drawings('polyline', { ...polylineCore }, () => polylineCore.all());
|
|
4715
|
-
/**
|
|
5836
|
+
const polylineNs: DrawingNamespace<typeof polylineCore, Polyline> = drawings('polyline', { ...polylineCore }, () => polylineCore.all());
|
|
5837
|
+
/**
|
|
5838
|
+
* Shapes through many chart points, straight or curved, open or closed and filled: `polyline.new()`,
|
|
5839
|
+
* `polyline.delete()`, `polyline.all`.
|
|
5840
|
+
*/
|
|
4716
5841
|
export const polyline = polylineNs as typeof polylineNs & {
|
|
4717
5842
|
new: ((args: PolylineNewArgs) => Polyline) & ((points: ChartPoint[], args: PolylineNewArgs) => Polyline);
|
|
4718
5843
|
};
|
|
4719
5844
|
|
|
4720
|
-
const tableNs = drawings('table', { ...tableCore }, () => tableCore.all());
|
|
5845
|
+
const tableNs: DrawingNamespace<typeof tableCore, Table> = drawings('table', { ...tableCore }, () => tableCore.all());
|
|
4721
5846
|
/**
|
|
4722
|
-
*
|
|
5847
|
+
* Tables fixed at a place of the pane, for values and dashboards: `table.new()` creates one, `table.cell()` fills it,
|
|
5848
|
+
* `table.all` lists the live tables. The live tables go to `result.tables`.
|
|
4723
5849
|
*/
|
|
4724
|
-
export const table = tableNs as typeof tableNs & {
|
|
5850
|
+
export const table: TableNamespace = tableNs as typeof tableNs & {
|
|
4725
5851
|
new: ((args: TableNewArgs) => Table) & ((position: string, columns: number, rows: number, args: TableNewArgs) => Table);
|
|
4726
5852
|
cell: ((args: TableCellArgs) => void) &
|
|
4727
5853
|
((table_id: Table, column: number, row: number, args: TableCellArgs) => void) &
|
|
4728
5854
|
((table_id: Table, column: number, row: number, text: string, args: TableCellArgs) => void);
|
|
4729
5855
|
};
|
|
5856
|
+
sameKeys<typeof tableNs, TableNamespace>(true);
|
|
4730
5857
|
|
|
4731
5858
|
/** PineScript `position.*` constants (table positions). */
|
|
4732
5859
|
export { position };
|
|
4733
5860
|
|
|
4734
|
-
/**
|
|
4735
|
-
export const text = { ...textCore };
|
|
5861
|
+
/** Text constants: `text.format_*` (bold, italic), `text.align_*` (alignment) and `text.wrap_*` (wrapping). */
|
|
5862
|
+
export const text: typeof textCore = { ...textCore };
|
|
4736
5863
|
|
|
4737
|
-
|
|
4738
|
-
|
|
4739
|
-
export const { shape, location, size, xloc, yloc, extend, display, format, font, scale, order, currency, adjustment } =
|
|
4740
|
-
pineConstants;
|
|
5864
|
+
// The constant namespaces (`shape.triangleup`, `size.small`, `xloc.bar_time`...), each documented in constants.ts.
|
|
5865
|
+
export { shape, location, size, xloc, yloc, extend, display, format, font, scale, order, currency, adjustment } from './constants.js';
|
|
4741
5866
|
|
|
4742
5867
|
/**
|
|
4743
5868
|
* PineScript `chart.point.*`. `chart.point.now(price?)` is the point of the current bar
|
|
4744
5869
|
* (index, time, and `price`, default the close), so it runs inside eachBar().
|
|
4745
5870
|
*/
|
|
4746
|
-
export const chart = {
|
|
5871
|
+
export const chart: ChartNamespace = {
|
|
4747
5872
|
/** Chart foreground colour (PineScript `chart.fg_color`), from the chart context. */
|
|
4748
5873
|
get fg_color(): string {
|
|
4749
5874
|
return chartText('foregroundColor', 'chart.fg_color');
|
|
@@ -4797,14 +5922,33 @@ export const chart = {
|
|
|
4797
5922
|
},
|
|
4798
5923
|
};
|
|
4799
5924
|
|
|
4800
|
-
/**
|
|
4801
|
-
*
|
|
5925
|
+
/**
|
|
5926
|
+
* Makes a Series from an array of numbers, one per bar (oldest first), e.g. values collected inside `eachBar()`.
|
|
5927
|
+
* @param values - One value per bar; NaN is na.
|
|
5928
|
+
* @returns Series of the values.
|
|
5929
|
+
* @example
|
|
5930
|
+
* ```js
|
|
5931
|
+
* const ranges = [];
|
|
5932
|
+
* eachBar((c) => { ranges.push(c.high - c.low); });
|
|
5933
|
+
* plot(seriesOf(ranges), "Range");
|
|
5934
|
+
* ```
|
|
5935
|
+
*/
|
|
4802
5936
|
export function seriesOf(values: number[]): Series {
|
|
4803
5937
|
collector();
|
|
4804
5938
|
return Series.fromArray(ctxBars, values);
|
|
4805
5939
|
}
|
|
4806
5940
|
|
|
4807
|
-
/**
|
|
5941
|
+
/**
|
|
5942
|
+
* Declares a condition users can create an alert on (in the app's alert dialog). It does not send an alert itself.
|
|
5943
|
+
* @param condition - Series that is true (non-zero) on the bars where the alert fires.
|
|
5944
|
+
* @param title - Name of the condition in the alert dialog.
|
|
5945
|
+
* @param message - Default text of the alert. Default: the title.
|
|
5946
|
+
* @example
|
|
5947
|
+
* ```js
|
|
5948
|
+
* const cross = ta.crossover(close, ta.sma(close, 50));
|
|
5949
|
+
* alertcondition(cross, "Price above SMA 50", "Close crossed above its 50-bar average");
|
|
5950
|
+
* ```
|
|
5951
|
+
*/
|
|
4808
5952
|
export function alertcondition(condition: Series, title: string, message?: string): void {
|
|
4809
5953
|
const c = collector();
|
|
4810
5954
|
const id = `alert${c.alertConfig.length}`;
|
|
@@ -4846,12 +5990,23 @@ function alertImpl(message: string | ReadonlyArray<string | undefined>, freq: Al
|
|
|
4846
5990
|
else for (let i = 0; i < b.length; i++) call(i);
|
|
4847
5991
|
}
|
|
4848
5992
|
|
|
4849
|
-
|
|
4850
|
-
export const alert = Object.assign(alertImpl, {
|
|
5993
|
+
const alertMembers = Object.assign(alertImpl, {
|
|
4851
5994
|
freq_all: 'all',
|
|
4852
5995
|
freq_once_per_bar: 'once_per_bar',
|
|
4853
5996
|
freq_once_per_bar_close: 'once_per_bar_close',
|
|
4854
5997
|
} as const);
|
|
5998
|
+
/**
|
|
5999
|
+
* Sends an alert message while the script runs (to the alerts set on the script), with the `alert.freq_*`
|
|
6000
|
+
* constants for how often it may fire.
|
|
6001
|
+
* @example
|
|
6002
|
+
* ```js
|
|
6003
|
+
* eachBar((c) => {
|
|
6004
|
+
* if (c.get(close) > c.get(high, 1)) alert("New high", alert.freq_once_per_bar_close);
|
|
6005
|
+
* });
|
|
6006
|
+
* ```
|
|
6007
|
+
*/
|
|
6008
|
+
export const alert: AlertApi = alertMembers;
|
|
6009
|
+
sameKeys<typeof alertMembers, AlertApi>(true);
|
|
4855
6010
|
|
|
4856
6011
|
// ── Logs (log.info / log.warning / log.error) ────────────────────────────────
|
|
4857
6012
|
|
|
@@ -4874,8 +6029,9 @@ export const MAX_LOG_ENTRIES = 10_000;
|
|
|
4874
6029
|
let logLineResolver: ((stack: string) => number | undefined) | null = null;
|
|
4875
6030
|
|
|
4876
6031
|
/**
|
|
4877
|
-
*
|
|
4878
|
-
* `stack`) and gives the line in the script's own source
|
|
6032
|
+
* Host-side: how the host finds the line of the script that called log.*(). Scripts never call it.
|
|
6033
|
+
* @param resolver - Gets the stack of the call (an Error's `stack`) and gives the line in the script's own source;
|
|
6034
|
+
* null (the default): messages have no line.
|
|
4879
6035
|
*/
|
|
4880
6036
|
export function setLogLineResolver(resolver: ((stack: string) => number | undefined) | null): void {
|
|
4881
6037
|
logLineResolver = resolver;
|
|
@@ -4904,14 +6060,7 @@ function logImpl(level: LogLevel, message: string | ReadonlyArray<string | undef
|
|
|
4904
6060
|
if (c.logs.length > MAX_LOG_ENTRIES * 2) c.logs.splice(0, c.logs.length - MAX_LOG_ENTRIES);
|
|
4905
6061
|
}
|
|
4906
6062
|
|
|
4907
|
-
|
|
4908
|
-
* PineScript `log.info()`, `log.warning()` and `log.error()`: a message for the host's logs panel, made on the current
|
|
4909
|
-
* bar inside eachBar() / strategy.eachBar(), on every bar at the top level of the script (which PineScript runs on
|
|
4910
|
-
* every bar; `message` is then a text or one text per bar, a bar whose text is na makes no message). With arguments,
|
|
4911
|
-
* `message` is a str.format() pattern (`log.info('close {0}', close)`), a Series argument giving its value on the bar.
|
|
4912
|
-
* The messages of a run are in `result.logs`, by bar ({@link MAX_LOG_ENTRIES} newest kept).
|
|
4913
|
-
*/
|
|
4914
|
-
export const log = strictNamespace('log', {
|
|
6063
|
+
const logMembers = strictNamespace('log', {
|
|
4915
6064
|
info(message: string | ReadonlyArray<string | undefined>, ...args: unknown[]): void {
|
|
4916
6065
|
logImpl('info', message, args);
|
|
4917
6066
|
},
|
|
@@ -4922,6 +6071,18 @@ export const log = strictNamespace('log', {
|
|
|
4922
6071
|
logImpl('error', message, args);
|
|
4923
6072
|
},
|
|
4924
6073
|
});
|
|
6074
|
+
/**
|
|
6075
|
+
* Messages for the logs panel: `log.info`, `log.warning` and `log.error`. Inside `eachBar()` a call makes a message on
|
|
6076
|
+
* the current bar; at the top level, one message per bar. With arguments the message is a `str.format()` pattern.
|
|
6077
|
+
* @example
|
|
6078
|
+
* ```js
|
|
6079
|
+
* eachBar((c) => {
|
|
6080
|
+
* if (c.get(volume) > 2 * c.get(ta.sma(volume, 20))) log.info("Volume spike: {0}", c.get(volume));
|
|
6081
|
+
* });
|
|
6082
|
+
* ```
|
|
6083
|
+
*/
|
|
6084
|
+
export const log: LogNamespace = logMembers;
|
|
6085
|
+
sameKeys<typeof logMembers, LogNamespace>(true);
|
|
4925
6086
|
|
|
4926
6087
|
/** The messages of a resumed run calculated from bar `from`: those of the run before on the bars before `from`, then the
|
|
4927
6088
|
* new ones on the bars from `from` (the top-level log calls of a resumed run make them again on every bar). */
|
|
@@ -4956,11 +6117,20 @@ export type {
|
|
|
4956
6117
|
StrategyVariable,
|
|
4957
6118
|
} from '../strategy/index.js';
|
|
4958
6119
|
|
|
4959
|
-
/** PineScript `math.*`; `math.round_to_mintick(x)` uses `syminfo.mintick` of the chart context. */
|
|
4960
6120
|
const { saveRandom: _saveRandom, restoreRandom: _restoreRandom, ...mathScript } = mathCore;
|
|
4961
6121
|
void _saveRandom;
|
|
4962
6122
|
void _restoreRandom;
|
|
4963
|
-
|
|
6123
|
+
/**
|
|
6124
|
+
* Math functions and constants for numbers and Series: rounding, min and max, powers and logarithms, trigonometry,
|
|
6125
|
+
* random numbers, `math.pi`... A Series argument gives a Series, numbers give a number. `math.round_to_mintick`
|
|
6126
|
+
* uses the symbol's tick size.
|
|
6127
|
+
* @example
|
|
6128
|
+
* ```js
|
|
6129
|
+
* const range = math.abs(close.sub(open));
|
|
6130
|
+
* plot(math.round(ta.sma(range, 10), 2), "Body");
|
|
6131
|
+
* ```
|
|
6132
|
+
*/
|
|
6133
|
+
export const math: Omit<typeof mathCore, 'saveRandom' | 'restoreRandom'> = strictNamespace('math', {
|
|
4964
6134
|
...mathScript,
|
|
4965
6135
|
// the generators start again on each run: a resumed run would draw other numbers (#206)
|
|
4966
6136
|
random: ((min?: number, max?: number, seed?: number) => {
|
|
@@ -4972,7 +6142,93 @@ export const math = strictNamespace('math', {
|
|
|
4972
6142
|
return number instanceof Series ? mathCore.round_to_mintick(number, tick) : mathCore.round_to_mintick(number, tick);
|
|
4973
6143
|
}) as typeof mathCore.round_to_mintick,
|
|
4974
6144
|
});
|
|
4975
|
-
|
|
6145
|
+
// ── calc: plain-English names ────────────────────────────────────────────────
|
|
6146
|
+
|
|
6147
|
+
/** A number as a Series of the bars of the run. */
|
|
6148
|
+
const asSeries = (v: Series | number): Series => (typeof v === 'number' ? Series.constant(ctxBars, v) : v);
|
|
6149
|
+
|
|
6150
|
+
/** The kinds of `calc.average()`. */
|
|
6151
|
+
const AVERAGE_KINDS: Record<string, (s: Series, n: number) => Series> = {
|
|
6152
|
+
simple: (s, n) => taSeries.sma(s, n),
|
|
6153
|
+
exponential: (s, n) => taSeries.ema(s, n),
|
|
6154
|
+
weighted: (s, n) => taSeries.wma(s, n),
|
|
6155
|
+
smoothed: (s, n) => taSeries.rma(s, n),
|
|
6156
|
+
hull: (s, n) => taSeries.hma(s, n),
|
|
6157
|
+
'volume-weighted': (s, n) => ta.vwma(s, n),
|
|
6158
|
+
};
|
|
6159
|
+
|
|
6160
|
+
function checkLength(fn: string, length: unknown): number {
|
|
6161
|
+
if (typeof length !== 'number' || !Number.isInteger(length) || length < 1) {
|
|
6162
|
+
throw new ScriptError(`calc.${fn}(): the length is a whole number of bars, 1 or more, got ${shown(length)}.`);
|
|
6163
|
+
}
|
|
6164
|
+
return length;
|
|
6165
|
+
}
|
|
6166
|
+
|
|
6167
|
+
/** The conditions of `calc.all()` / `calc.any()` as Series; at least one is needed. */
|
|
6168
|
+
function conditionsOf(name: string, conditions: Array<Series | number>): Series[] {
|
|
6169
|
+
if (!conditions.length) throw new ScriptError(`${name}(): give at least one condition, e.g. ${name}(close.gt(open), volume.gt(0)).`);
|
|
6170
|
+
return conditions.map(asSeries);
|
|
6171
|
+
}
|
|
6172
|
+
|
|
6173
|
+
const calcMembers = strictNamespace('calc', outsideBarLoops({
|
|
6174
|
+
/** Moving average of the last `length` values: kind 'simple' (default), 'exponential', 'weighted', 'smoothed', 'hull' or 'volume-weighted'. */
|
|
6175
|
+
average(source: Series | number, length: number, kind: string = 'simple'): Series {
|
|
6176
|
+
const fn = AVERAGE_KINDS[kind];
|
|
6177
|
+
if (!fn) throw new ScriptError(`calc.average(): the kind is one of ${Object.keys(AVERAGE_KINDS).map((k) => `'${k}'`).join(', ')}, got ${shown(kind)}.`);
|
|
6178
|
+
return fn(asSeries(source), checkLength('average', length));
|
|
6179
|
+
},
|
|
6180
|
+
/** 1 on the bar where `a` crosses above `b`. */
|
|
6181
|
+
crossesAbove: (a: Series | number, b: Series | number): Series => ta.crossover(asSeries(a), b),
|
|
6182
|
+
/** 1 on the bar where `a` crosses below `b`. */
|
|
6183
|
+
crossesBelow: (a: Series | number, b: Series | number): Series => ta.crossunder(asSeries(a), b),
|
|
6184
|
+
/** 1 on the bar where `a` and `b` cross, either way. */
|
|
6185
|
+
crosses: (a: Series | number, b: Series | number): Series => ta.cross(asSeries(a), asSeries(b)),
|
|
6186
|
+
/** 1 where `a` is above `b`. */
|
|
6187
|
+
above: (a: Series | number, b: Series | number): Series => asSeries(a).gt(b),
|
|
6188
|
+
/** 1 where `a` is below `b`. */
|
|
6189
|
+
below: (a: Series | number, b: Series | number): Series => asSeries(a).lt(b),
|
|
6190
|
+
/** 1 where `value` is between `low` and `high` (both included). */
|
|
6191
|
+
between: (value: Series | number, lowLimit: Series | number, highLimit: Series | number): Series =>
|
|
6192
|
+
asSeries(value).gte(lowLimit).and(asSeries(value).lte(highLimit)),
|
|
6193
|
+
/** The value `bars` bars before (1: the previous bar). */
|
|
6194
|
+
previous: (source: Series | number, bars: number = 1): Series => asSeries(source).offset(checkLength('previous', bars)),
|
|
6195
|
+
/** The difference with the value `bars` bars before. */
|
|
6196
|
+
change: (source: Series | number, bars: number = 1): Series => taSeries.change(asSeries(source), checkLength('change', bars)),
|
|
6197
|
+
/** The change in percent since `bars` bars before. */
|
|
6198
|
+
percentChange: (source: Series | number, bars: number = 1): Series => {
|
|
6199
|
+
const s = asSeries(source);
|
|
6200
|
+
const before = s.offset(checkLength('percentChange', bars));
|
|
6201
|
+
return s.sub(before).div(before).mul(100);
|
|
6202
|
+
},
|
|
6203
|
+
/** The highest value of the last `length` bars. */
|
|
6204
|
+
highest: (source: Series | number, length: number): Series => ta.highest(asSeries(source), checkLength('highest', length)),
|
|
6205
|
+
/** The lowest value of the last `length` bars. */
|
|
6206
|
+
lowest: (source: Series | number, length: number): Series => ta.lowest(asSeries(source), checkLength('lowest', length)),
|
|
6207
|
+
/** 1 when the value rose on each of the last `bars` bars. */
|
|
6208
|
+
isRising: (source: Series | number, bars: number = 1): Series => taSeries.rising(asSeries(source), checkLength('isRising', bars)),
|
|
6209
|
+
/** 1 when the value fell on each of the last `bars` bars. */
|
|
6210
|
+
isFalling: (source: Series | number, bars: number = 1): Series => taSeries.falling(asSeries(source), checkLength('isFalling', bars)),
|
|
6211
|
+
/** Standard deviation of the last `length` values. */
|
|
6212
|
+
standardDeviation: (source: Series | number, length: number): Series => taSeries.stdev(asSeries(source), checkLength('standardDeviation', length)),
|
|
6213
|
+
/** `whenTrue` where the condition holds, else `whenFalse`. */
|
|
6214
|
+
ifElse: (condition: Series | number, whenTrue: Series | number, whenFalse: Series | number): Series => asSeries(condition).iff(whenTrue, whenFalse),
|
|
6215
|
+
/** 1 where every condition holds. */
|
|
6216
|
+
all: (...conditions: Array<Series | number>): Series => conditionsOf('calc.all', conditions).reduce((x, y) => x.and(y)),
|
|
6217
|
+
/** 1 where one of the conditions holds. */
|
|
6218
|
+
any: (...conditions: Array<Series | number>): Series => conditionsOf('calc.any', conditions).reduce((x, y) => x.or(y)),
|
|
6219
|
+
}, 'calc'));
|
|
6220
|
+
/**
|
|
6221
|
+
* Plain-English names for the most used calculations (`calc.average`, `calc.crossesAbove`...), beside the `ta.*` ones.
|
|
6222
|
+
* They take Series or numbers and give a Series; a condition gives 1 where true and 0 where false.
|
|
6223
|
+
*/
|
|
6224
|
+
export const calc: CalcNamespace = calcMembers;
|
|
6225
|
+
sameKeys<typeof calcMembers, CalcNamespace>(true);
|
|
6226
|
+
|
|
6227
|
+
/**
|
|
6228
|
+
* Comparisons of two numbers with a tolerance of 1e-10 (`compare.eq(0.1 + 0.2, 0.3)` is true), for the plain numbers
|
|
6229
|
+
* of a bar loop.
|
|
6230
|
+
*/
|
|
6231
|
+
export const compare = compareCore;
|
|
4976
6232
|
export { isInputActive } from '../runtime/input-active.js';
|
|
4977
6233
|
export type {
|
|
4978
6234
|
Bar,
|
|
@@ -5010,3 +6266,26 @@ export type {
|
|
|
5010
6266
|
PineSize,
|
|
5011
6267
|
ShapeStyle,
|
|
5012
6268
|
};
|
|
6269
|
+
|
|
6270
|
+
// ── defineIndicator ─────────────────────────────────────────────────────────
|
|
6271
|
+
|
|
6272
|
+
export {
|
|
6273
|
+
defineIndicator,
|
|
6274
|
+
type DefineIndicatorOptions,
|
|
6275
|
+
type IndicatorCalculation,
|
|
6276
|
+
type IndicatorDefinition,
|
|
6277
|
+
type IndicatorLiveRun,
|
|
6278
|
+
} from './define.js';
|
|
6279
|
+
export { formula, evaluateFormula, FORMULA_FUNCTIONS, type FormulaVariables } from './formula.js';
|
|
6280
|
+
export {
|
|
6281
|
+
defineIndicatorFromJson,
|
|
6282
|
+
indicatorBodyFromJson,
|
|
6283
|
+
checkIndicatorJson,
|
|
6284
|
+
type IndicatorJson,
|
|
6285
|
+
type JsonInput,
|
|
6286
|
+
type JsonPlot,
|
|
6287
|
+
type JsonLevel,
|
|
6288
|
+
type JsonFill,
|
|
6289
|
+
type JsonSignal,
|
|
6290
|
+
type JsonColorRule,
|
|
6291
|
+
} from './json.js';
|