oakscriptjs 0.24.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -1
- package/bin/oakscript.mjs +10 -3
- package/dist/cjs/box/index.d.ts +348 -289
- package/dist/cjs/box/index.d.ts.map +1 -1
- package/dist/cjs/box/index.js.map +2 -2
- package/dist/cjs/check/node.d.ts.map +1 -1
- package/dist/cjs/check/node.js +1 -0
- package/dist/cjs/check/node.js.map +2 -2
- package/dist/cjs/check/preview.d.ts +31 -0
- package/dist/cjs/check/preview.d.ts.map +1 -0
- package/dist/cjs/check/preview.js +303 -0
- package/dist/cjs/check/preview.js.map +7 -0
- package/dist/cjs/color/index.d.ts +11 -11
- package/dist/cjs/color/index.js.map +1 -1
- package/dist/cjs/color/parse.d.ts +2 -0
- package/dist/cjs/color/parse.d.ts.map +1 -1
- package/dist/cjs/color/parse.js +6 -0
- package/dist/cjs/color/parse.js.map +2 -2
- package/dist/cjs/compare/index.d.ts +76 -12
- package/dist/cjs/compare/index.d.ts.map +1 -1
- package/dist/cjs/compare/index.js.map +2 -2
- package/dist/cjs/drawing/registry.d.ts +28 -5
- package/dist/cjs/drawing/registry.d.ts.map +1 -1
- package/dist/cjs/drawing/registry.js +14 -0
- package/dist/cjs/drawing/registry.js.map +2 -2
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/label/index.d.ts +265 -187
- package/dist/cjs/label/index.d.ts.map +1 -1
- package/dist/cjs/label/index.js +1 -1
- package/dist/cjs/label/index.js.map +2 -2
- package/dist/cjs/line/index.d.ts +247 -207
- package/dist/cjs/line/index.d.ts.map +1 -1
- package/dist/cjs/line/index.js.map +2 -2
- package/dist/cjs/linefill/index.d.ts +61 -89
- package/dist/cjs/linefill/index.d.ts.map +1 -1
- package/dist/cjs/linefill/index.js.map +2 -2
- package/dist/cjs/math/index.d.ts +49 -40
- package/dist/cjs/math/index.d.ts.map +1 -1
- package/dist/cjs/math/index.js.map +2 -2
- package/dist/cjs/polyline/index.d.ts +57 -78
- package/dist/cjs/polyline/index.d.ts.map +1 -1
- package/dist/cjs/polyline/index.js.map +2 -2
- package/dist/cjs/runtime/input-active.d.ts +2 -2
- package/dist/cjs/runtime/input-active.js.map +1 -1
- package/dist/cjs/runtime/series.d.ts +241 -161
- package/dist/cjs/runtime/series.d.ts.map +1 -1
- package/dist/cjs/runtime/series.js +223 -127
- package/dist/cjs/runtime/series.js.map +2 -2
- package/dist/cjs/script/api/alert.d.ts +37 -0
- package/dist/cjs/script/api/alert.d.ts.map +1 -0
- package/dist/cjs/script/api/alert.js +17 -0
- package/dist/cjs/script/api/alert.js.map +7 -0
- package/dist/cjs/script/api/calc.d.ts +232 -0
- package/dist/cjs/script/api/calc.d.ts.map +1 -0
- package/dist/cjs/script/api/calc.js +17 -0
- package/dist/cjs/script/api/calc.js.map +7 -0
- package/dist/cjs/script/api/color.d.ts +213 -0
- package/dist/cjs/script/api/color.d.ts.map +1 -0
- package/dist/cjs/script/api/color.js +17 -0
- package/dist/cjs/script/api/color.js.map +7 -0
- package/dist/cjs/script/api/context.d.ts +764 -0
- package/dist/cjs/script/api/context.d.ts.map +1 -0
- package/dist/cjs/script/api/context.js +17 -0
- package/dist/cjs/script/api/context.js.map +7 -0
- package/dist/cjs/script/api/log.d.ts +58 -0
- package/dist/cjs/script/api/log.d.ts.map +1 -0
- package/dist/cjs/script/api/log.js +17 -0
- package/dist/cjs/script/api/log.js.map +7 -0
- package/dist/cjs/script/api/strategy.d.ts +391 -0
- package/dist/cjs/script/api/strategy.d.ts.map +1 -0
- package/dist/cjs/script/api/strategy.js +17 -0
- package/dist/cjs/script/api/strategy.js.map +7 -0
- package/dist/cjs/script/api/ta.d.ts +1012 -0
- package/dist/cjs/script/api/ta.d.ts.map +1 -0
- package/dist/cjs/script/api/ta.js +17 -0
- package/dist/cjs/script/api/ta.js.map +7 -0
- package/dist/cjs/script/api/table.d.ts +479 -0
- package/dist/cjs/script/api/table.d.ts.map +1 -0
- package/dist/cjs/script/api/table.js +17 -0
- package/dist/cjs/script/api/table.js.map +7 -0
- package/dist/cjs/script/constants.d.ts +228 -83
- package/dist/cjs/script/constants.d.ts.map +1 -1
- package/dist/cjs/script/constants.js +87 -0
- package/dist/cjs/script/constants.js.map +2 -2
- package/dist/cjs/script/define.d.ts +94 -0
- package/dist/cjs/script/define.d.ts.map +1 -0
- package/dist/cjs/script/define.js +127 -0
- package/dist/cjs/script/define.js.map +7 -0
- package/dist/cjs/script/drawing-args.d.ts.map +1 -1
- package/dist/cjs/script/drawing-args.js +1 -1
- package/dist/cjs/script/drawing-args.js.map +2 -2
- package/dist/cjs/script/formula.d.ts +53 -0
- package/dist/cjs/script/formula.d.ts.map +1 -0
- package/dist/cjs/script/formula.js +402 -0
- package/dist/cjs/script/formula.js.map +7 -0
- package/dist/cjs/script/globals.d.ts +10 -0
- package/dist/cjs/script/globals.d.ts.map +1 -1
- package/dist/cjs/script/globals.js.map +1 -1
- package/dist/cjs/script/index.d.ts +1065 -1006
- package/dist/cjs/script/index.d.ts.map +1 -1
- package/dist/cjs/script/index.js +530 -60
- package/dist/cjs/script/index.js.map +3 -3
- package/dist/cjs/script/json.d.ts +117 -0
- package/dist/cjs/script/json.d.ts.map +1 -0
- package/dist/cjs/script/json.js +321 -0
- package/dist/cjs/script/json.js.map +7 -0
- package/dist/cjs/str/index.d.ts +50 -75
- package/dist/cjs/str/index.d.ts.map +1 -1
- package/dist/cjs/str/index.js +2 -2
- package/dist/cjs/str/index.js.map +2 -2
- package/dist/cjs/strategy/index.d.ts +102 -1
- package/dist/cjs/strategy/index.d.ts.map +1 -1
- package/dist/cjs/strategy/index.js.map +2 -2
- package/dist/cjs/table/index.d.ts +330 -49
- package/dist/cjs/table/index.d.ts.map +1 -1
- package/dist/cjs/table/index.js +55 -27
- package/dist/cjs/table/index.js.map +2 -2
- package/dist/cjs/text/index.d.ts +12 -14
- package/dist/cjs/text/index.d.ts.map +1 -1
- package/dist/cjs/text/index.js.map +2 -2
- package/dist/cjs/types/index.d.ts +15 -8
- package/dist/cjs/types/index.d.ts.map +1 -1
- package/dist/cjs/types/index.js +12 -3
- package/dist/cjs/types/index.js.map +2 -2
- package/dist/esm/box/index.d.ts +348 -289
- package/dist/esm/box/index.d.ts.map +1 -1
- package/dist/esm/box/index.js +276 -276
- package/dist/esm/box/index.js.map +1 -1
- package/dist/esm/check/node.d.ts.map +1 -1
- package/dist/esm/check/node.js +1 -0
- package/dist/esm/check/node.js.map +1 -1
- package/dist/esm/check/preview.d.ts +31 -0
- package/dist/esm/check/preview.d.ts.map +1 -0
- package/dist/esm/check/preview.js +296 -0
- package/dist/esm/check/preview.js.map +1 -0
- package/dist/esm/color/index.d.ts +11 -11
- package/dist/esm/color/index.js +11 -11
- package/dist/esm/color/parse.d.ts +2 -0
- package/dist/esm/color/parse.d.ts.map +1 -1
- package/dist/esm/color/parse.js +7 -0
- package/dist/esm/color/parse.js.map +1 -1
- package/dist/esm/compare/index.d.ts +76 -12
- package/dist/esm/compare/index.d.ts.map +1 -1
- package/dist/esm/compare/index.js +76 -12
- package/dist/esm/compare/index.js.map +1 -1
- package/dist/esm/drawing/registry.d.ts +28 -5
- package/dist/esm/drawing/registry.d.ts.map +1 -1
- package/dist/esm/drawing/registry.js +39 -3
- package/dist/esm/drawing/registry.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/label/index.d.ts +265 -187
- package/dist/esm/label/index.d.ts.map +1 -1
- package/dist/esm/label/index.js +207 -177
- package/dist/esm/label/index.js.map +1 -1
- package/dist/esm/line/index.d.ts +247 -207
- package/dist/esm/line/index.d.ts.map +1 -1
- package/dist/esm/line/index.js +202 -194
- package/dist/esm/line/index.js.map +1 -1
- package/dist/esm/linefill/index.d.ts +61 -89
- package/dist/esm/linefill/index.d.ts.map +1 -1
- package/dist/esm/linefill/index.js +61 -89
- package/dist/esm/linefill/index.js.map +1 -1
- package/dist/esm/math/index.d.ts +49 -40
- package/dist/esm/math/index.d.ts.map +1 -1
- package/dist/esm/math/index.js +22 -9
- package/dist/esm/math/index.js.map +1 -1
- package/dist/esm/polyline/index.d.ts +57 -78
- package/dist/esm/polyline/index.d.ts.map +1 -1
- package/dist/esm/polyline/index.js +57 -78
- package/dist/esm/polyline/index.js.map +1 -1
- package/dist/esm/runtime/input-active.d.ts +2 -2
- package/dist/esm/runtime/input-active.js +2 -2
- package/dist/esm/runtime/series.d.ts +241 -161
- package/dist/esm/runtime/series.d.ts.map +1 -1
- package/dist/esm/runtime/series.js +241 -161
- package/dist/esm/runtime/series.js.map +1 -1
- package/dist/esm/script/api/alert.d.ts +37 -0
- package/dist/esm/script/api/alert.d.ts.map +1 -0
- package/dist/esm/script/api/alert.js +7 -0
- package/dist/esm/script/api/alert.js.map +1 -0
- package/dist/esm/script/api/calc.d.ts +232 -0
- package/dist/esm/script/api/calc.d.ts.map +1 -0
- package/dist/esm/script/api/calc.js +6 -0
- package/dist/esm/script/api/calc.js.map +1 -0
- package/dist/esm/script/api/color.d.ts +213 -0
- package/dist/esm/script/api/color.d.ts.map +1 -0
- package/dist/esm/script/api/color.js +6 -0
- package/dist/esm/script/api/color.js.map +1 -0
- package/dist/esm/script/api/context.d.ts +764 -0
- package/dist/esm/script/api/context.d.ts.map +1 -0
- package/dist/esm/script/api/context.js +7 -0
- package/dist/esm/script/api/context.js.map +1 -0
- package/dist/esm/script/api/log.d.ts +58 -0
- package/dist/esm/script/api/log.d.ts.map +1 -0
- package/dist/esm/script/api/log.js +6 -0
- package/dist/esm/script/api/log.js.map +1 -0
- package/dist/esm/script/api/strategy.d.ts +391 -0
- package/dist/esm/script/api/strategy.d.ts.map +1 -0
- package/dist/esm/script/api/strategy.js +7 -0
- package/dist/esm/script/api/strategy.js.map +1 -0
- package/dist/esm/script/api/ta.d.ts +1012 -0
- package/dist/esm/script/api/ta.d.ts.map +1 -0
- package/dist/esm/script/api/ta.js +6 -0
- package/dist/esm/script/api/ta.js.map +1 -0
- package/dist/esm/script/api/table.d.ts +479 -0
- package/dist/esm/script/api/table.d.ts.map +1 -0
- package/dist/esm/script/api/table.js +7 -0
- package/dist/esm/script/api/table.js.map +1 -0
- package/dist/esm/script/constants.d.ts +228 -83
- package/dist/esm/script/constants.d.ts.map +1 -1
- package/dist/esm/script/constants.js +110 -24
- package/dist/esm/script/constants.js.map +1 -1
- package/dist/esm/script/define.d.ts +94 -0
- package/dist/esm/script/define.d.ts.map +1 -0
- package/dist/esm/script/define.js +136 -0
- package/dist/esm/script/define.js.map +1 -0
- package/dist/esm/script/drawing-args.d.ts.map +1 -1
- package/dist/esm/script/drawing-args.js +2 -1
- package/dist/esm/script/drawing-args.js.map +1 -1
- package/dist/esm/script/formula.d.ts +53 -0
- package/dist/esm/script/formula.d.ts.map +1 -0
- package/dist/esm/script/formula.js +408 -0
- package/dist/esm/script/formula.js.map +1 -0
- package/dist/esm/script/globals.d.ts +10 -0
- package/dist/esm/script/globals.d.ts.map +1 -1
- package/dist/esm/script/globals.js.map +1 -1
- package/dist/esm/script/index.d.ts +1065 -1006
- package/dist/esm/script/index.d.ts.map +1 -1
- package/dist/esm/script/index.js +1096 -151
- package/dist/esm/script/index.js.map +1 -1
- package/dist/esm/script/json.d.ts +117 -0
- package/dist/esm/script/json.d.ts.map +1 -0
- package/dist/esm/script/json.js +375 -0
- package/dist/esm/script/json.js.map +1 -0
- package/dist/esm/str/index.d.ts +50 -75
- package/dist/esm/str/index.d.ts.map +1 -1
- package/dist/esm/str/index.js +51 -76
- package/dist/esm/str/index.js.map +1 -1
- package/dist/esm/strategy/index.d.ts +102 -1
- package/dist/esm/strategy/index.d.ts.map +1 -1
- package/dist/esm/strategy/index.js +1 -1
- package/dist/esm/strategy/index.js.map +1 -1
- package/dist/esm/table/index.d.ts +330 -49
- package/dist/esm/table/index.d.ts.map +1 -1
- package/dist/esm/table/index.js +372 -61
- package/dist/esm/table/index.js.map +1 -1
- package/dist/esm/text/index.d.ts +12 -14
- package/dist/esm/text/index.d.ts.map +1 -1
- package/dist/esm/text/index.js +12 -14
- package/dist/esm/text/index.js.map +1 -1
- package/dist/esm/types/index.d.ts +15 -8
- package/dist/esm/types/index.d.ts.map +1 -1
- package/dist/esm/types/index.js +15 -8
- package/dist/esm/types/index.js.map +1 -1
- package/docs/first-indicator.md +152 -0
- package/docs/guide.md +1185 -0
- package/docs/inventory.md +772 -0
- package/docs/no-code.md +207 -0
- package/docs/recipes.md +202 -0
- package/package.json +2 -1
- package/skills/oakscript/SKILL.md +8 -0
- package/skills/oakscript/reference/errors.md +3 -2
- package/src/box/index.ts +348 -289
- package/src/check/node.ts +1 -0
- package/src/check/preview.ts +307 -0
- package/src/color/index.ts +11 -11
- package/src/color/parse.ts +7 -0
- package/src/compare/index.ts +76 -12
- package/src/drawing/registry.ts +44 -5
- package/src/index.ts +1 -1
- package/src/label/index.ts +267 -189
- package/src/line/index.ts +248 -208
- package/src/linefill/index.ts +61 -89
- package/src/math/index.ts +51 -42
- package/src/polyline/index.ts +57 -78
- package/src/runtime/input-active.ts +2 -2
- package/src/runtime/series.ts +243 -163
- package/src/script/api/alert.ts +43 -0
- package/src/script/api/calc.ts +250 -0
- package/src/script/api/color.ts +245 -0
- package/src/script/api/context.ts +944 -0
- package/src/script/api/log.ts +60 -0
- package/src/script/api/strategy.ts +410 -0
- package/src/script/api/ta.ts +1115 -0
- package/src/script/api/table.ts +538 -0
- package/src/script/constants.ts +229 -25
- package/src/script/define.ts +221 -0
- package/src/script/drawing-args.ts +2 -1
- package/src/script/formula.ts +438 -0
- package/src/script/globals.ts +10 -0
- package/src/script/index.ts +1517 -239
- package/src/script/json.ts +457 -0
- package/src/str/index.ts +51 -76
- package/src/strategy/index.ts +102 -1
- package/src/table/index.ts +388 -62
- package/src/text/index.ts +12 -14
- package/src/types/index.ts +15 -8
package/src/check/node.ts
CHANGED
|
@@ -33,6 +33,7 @@ import {
|
|
|
33
33
|
} from './index.js';
|
|
34
34
|
|
|
35
35
|
const USAGE = `Usage: oakscript check <script.js> [options]
|
|
36
|
+
oakscript preview <script.js | indicator.json> (a live chart in the browser: oakscript preview --help)
|
|
36
37
|
|
|
37
38
|
Runs an OakScript script like a host (declarations, then a run on bars) and reports its inputs, outputs, values,
|
|
38
39
|
signals, trades, errors with their line, and warnings for the mistakes that give no error.
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `oakscript preview <file>`: a chart of a script (`.js`, the format of `oakscript check`) or of an indicator in JSON
|
|
3
|
+
* (`.json`, see `defineIndicatorFromJson`) in the browser, drawn again each time the file is saved. The settings of the
|
|
4
|
+
* indicator are a form beside the chart; a mistake shows as a message above it. Node.js only, no dependency: the page
|
|
5
|
+
* loads lightweight-charts from the project's node_modules when it is installed, else from a CDN.
|
|
6
|
+
*/
|
|
7
|
+
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
|
|
8
|
+
import { existsSync, readFileSync, watch, type FSWatcher } from 'node:fs';
|
|
9
|
+
import { createRequire } from 'node:module';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import type { Bar } from '../types/index.js';
|
|
12
|
+
import { executeScript, indicatorBodyFromJson } from '../script/index.js';
|
|
13
|
+
import { compileScript, syntheticBars, testChart } from './harness.js';
|
|
14
|
+
import { readBars } from './node.js';
|
|
15
|
+
|
|
16
|
+
export interface PreviewOptions {
|
|
17
|
+
/** The script (.js) or the indicator in JSON (.json). */
|
|
18
|
+
file: string;
|
|
19
|
+
/** Bars to draw (CSV or JSON file); default: 500 synthetic daily bars. */
|
|
20
|
+
barsFile?: string;
|
|
21
|
+
/** Port (default 4173; 0: any free port). */
|
|
22
|
+
port?: number;
|
|
23
|
+
/** Host to listen on (default 0.0.0.0: the page opens from another computer of the network too). */
|
|
24
|
+
host?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface PreviewServer {
|
|
28
|
+
url: string;
|
|
29
|
+
port: number;
|
|
30
|
+
server: Server;
|
|
31
|
+
close(): Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const CDN = 'https://unpkg.com/lightweight-charts@5/dist/lightweight-charts.standalone.production.js';
|
|
35
|
+
|
|
36
|
+
/** The standalone build of lightweight-charts in the project of `from`, when it is installed. */
|
|
37
|
+
function localChartLibrary(from: string): string | null {
|
|
38
|
+
try {
|
|
39
|
+
const require = createRequire(path.resolve(from, 'package.json'));
|
|
40
|
+
const pkg = require.resolve('lightweight-charts/package.json');
|
|
41
|
+
const file = path.join(path.dirname(pkg), 'dist', 'lightweight-charts.standalone.production.js');
|
|
42
|
+
return existsSync(file) ? file : null;
|
|
43
|
+
} catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** One run of the file on the bars: what the page draws, or the error. */
|
|
49
|
+
export function previewRun(file: string, bars: Bar[], inputs: Record<string, unknown> = {}): Record<string, unknown> {
|
|
50
|
+
try {
|
|
51
|
+
const source = readFileSync(file, 'utf8');
|
|
52
|
+
const body = file.toLowerCase().endsWith('.json') ? indicatorBodyFromJson(source) : compileScript(source);
|
|
53
|
+
const run = executeScript(body, bars, inputs, testChart(bars), { strict: true, palette: true });
|
|
54
|
+
return {
|
|
55
|
+
ok: true,
|
|
56
|
+
metadata: run.metadata,
|
|
57
|
+
inputConfig: run.inputConfig,
|
|
58
|
+
plotConfig: run.plotConfig,
|
|
59
|
+
hlineConfig: run.hlineConfig,
|
|
60
|
+
result: run.result,
|
|
61
|
+
warnings: run.warnings,
|
|
62
|
+
};
|
|
63
|
+
} catch (err) {
|
|
64
|
+
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Starts the preview server; `close()` stops it and the file watch. */
|
|
69
|
+
export function startPreview(options: PreviewOptions): Promise<PreviewServer> {
|
|
70
|
+
const file = path.resolve(options.file);
|
|
71
|
+
if (!existsSync(file)) return Promise.reject(new Error(`oakscript preview: there is no file ${file}`));
|
|
72
|
+
const bars = options.barsFile ? readBars(path.resolve(options.barsFile)) : syntheticBars(500, 86400);
|
|
73
|
+
const lib = localChartLibrary(path.dirname(file)) ?? localChartLibrary(process.cwd());
|
|
74
|
+
const clients = new Set<ServerResponse>();
|
|
75
|
+
let watcher: FSWatcher | null = null;
|
|
76
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
77
|
+
|
|
78
|
+
const handle = (req: IncomingMessage, res: ServerResponse): void => {
|
|
79
|
+
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
80
|
+
if (url.pathname === '/') {
|
|
81
|
+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
|
|
82
|
+
res.end(page(path.basename(file), lib ? '/lightweight-charts.js' : CDN));
|
|
83
|
+
} else if (url.pathname === '/lightweight-charts.js' && lib) {
|
|
84
|
+
res.writeHead(200, { 'content-type': 'text/javascript' });
|
|
85
|
+
res.end(readFileSync(lib));
|
|
86
|
+
} else if (url.pathname === '/run') {
|
|
87
|
+
let inputs: Record<string, unknown>;
|
|
88
|
+
try {
|
|
89
|
+
inputs = JSON.parse(url.searchParams.get('inputs') ?? '{}') as Record<string, unknown>;
|
|
90
|
+
} catch {
|
|
91
|
+
inputs = {};
|
|
92
|
+
}
|
|
93
|
+
res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
94
|
+
res.end(JSON.stringify({ ...previewRun(file, bars, inputs), bars }));
|
|
95
|
+
} else if (url.pathname === '/events') {
|
|
96
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' });
|
|
97
|
+
res.write(': connected\n\n');
|
|
98
|
+
clients.add(res);
|
|
99
|
+
req.on('close', () => clients.delete(res));
|
|
100
|
+
} else {
|
|
101
|
+
res.writeHead(404);
|
|
102
|
+
res.end();
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const server = createServer(handle);
|
|
107
|
+
watcher = watch(file, () => {
|
|
108
|
+
if (timer) clearTimeout(timer);
|
|
109
|
+
timer = setTimeout(() => {
|
|
110
|
+
for (const c of clients) c.write('data: changed\n\n');
|
|
111
|
+
}, 100);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
return new Promise((resolve, reject) => {
|
|
115
|
+
server.once('error', reject);
|
|
116
|
+
server.listen(options.port ?? 4173, options.host ?? '0.0.0.0', () => {
|
|
117
|
+
const address = server.address();
|
|
118
|
+
const port = typeof address === 'object' && address ? address.port : options.port ?? 4173;
|
|
119
|
+
resolve({
|
|
120
|
+
url: `http://localhost:${port}/`,
|
|
121
|
+
port,
|
|
122
|
+
server,
|
|
123
|
+
close: () =>
|
|
124
|
+
new Promise<void>((done) => {
|
|
125
|
+
watcher?.close();
|
|
126
|
+
if (timer) clearTimeout(timer);
|
|
127
|
+
for (const c of clients) c.end();
|
|
128
|
+
clients.clear();
|
|
129
|
+
server.close(() => done());
|
|
130
|
+
}),
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const PREVIEW_USAGE = `Usage: oakscript preview <script.js | indicator.json> [options]
|
|
137
|
+
|
|
138
|
+
Draws the indicator on a chart in the browser and draws it again each time the file is saved. Its settings are a
|
|
139
|
+
form beside the chart; a mistake shows above it.
|
|
140
|
+
|
|
141
|
+
Options:
|
|
142
|
+
--bars <file.csv|json> bars to draw (time, open, high, low, close, volume); default: 500 synthetic daily bars
|
|
143
|
+
--port <n> port (default 4173)
|
|
144
|
+
--host <address> address to listen on (default 0.0.0.0)`;
|
|
145
|
+
|
|
146
|
+
/** `oakscript preview` of the command line: starts the server and prints its address. */
|
|
147
|
+
export async function previewMain(argv: string[], print: (text: string) => void = (t) => process.stdout.write(t + '\n')): Promise<number> {
|
|
148
|
+
const args = argv[0] === 'preview' ? argv.slice(1) : [...argv];
|
|
149
|
+
if (!args.length || args.includes('--help') || args.includes('-h')) {
|
|
150
|
+
print(PREVIEW_USAGE);
|
|
151
|
+
return args.length ? 0 : 1;
|
|
152
|
+
}
|
|
153
|
+
const o: PreviewOptions = { file: '' };
|
|
154
|
+
for (let k = 0; k < args.length; k++) {
|
|
155
|
+
const a = args[k]!;
|
|
156
|
+
const next = (): string => {
|
|
157
|
+
const v = args[++k];
|
|
158
|
+
if (v === undefined) throw new Error(`${a} needs a value`);
|
|
159
|
+
return v;
|
|
160
|
+
};
|
|
161
|
+
if (a === '--bars') o.barsFile = next();
|
|
162
|
+
else if (a === '--port') o.port = Number(next());
|
|
163
|
+
else if (a === '--host') o.host = next();
|
|
164
|
+
else if (a.startsWith('--')) {
|
|
165
|
+
print(`Unknown option ${a}\n\n${PREVIEW_USAGE}`);
|
|
166
|
+
return 1;
|
|
167
|
+
} else o.file = a;
|
|
168
|
+
}
|
|
169
|
+
try {
|
|
170
|
+
const p = await startPreview(o);
|
|
171
|
+
print(`Preview of ${o.file}: ${p.url} (open it in a browser; it updates when the file is saved, Ctrl+C stops)`);
|
|
172
|
+
return 0;
|
|
173
|
+
} catch (err) {
|
|
174
|
+
print(err instanceof Error ? err.message : String(err));
|
|
175
|
+
return 1;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** The page: the chart, the settings form, the messages; it asks /run again on each change of the file. */
|
|
180
|
+
function page(name: string, library: string): string {
|
|
181
|
+
return `<!doctype html>
|
|
182
|
+
<html lang="en">
|
|
183
|
+
<head>
|
|
184
|
+
<meta charset="utf-8">
|
|
185
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
186
|
+
<title>${escapeHtml(name)} – preview</title>
|
|
187
|
+
<style>
|
|
188
|
+
body { margin: 0; font: 14px system-ui, sans-serif; background: #131722; color: #d1d4dc; display: flex; height: 100vh; }
|
|
189
|
+
#main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
|
|
190
|
+
#head { padding: 8px 12px; border-bottom: 1px solid #2a2e39; }
|
|
191
|
+
#title { font-weight: 600; }
|
|
192
|
+
#msg { white-space: pre-wrap; font-family: ui-monospace, monospace; padding: 8px 12px; display: none; }
|
|
193
|
+
#msg.error { display: block; background: #4a1c1f; color: #ffb4b4; }
|
|
194
|
+
#msg.warn { display: block; background: #4a3b12; color: #ffe08a; }
|
|
195
|
+
#chart { flex: 1; min-height: 0; }
|
|
196
|
+
#side { width: 260px; border-left: 1px solid #2a2e39; padding: 12px; overflow: auto; }
|
|
197
|
+
#side h3 { margin: 0 0 8px; font-size: 13px; text-transform: uppercase; color: #868993; }
|
|
198
|
+
label { display: block; margin: 0 0 10px; }
|
|
199
|
+
label span { display: block; margin-bottom: 3px; color: #b2b5be; }
|
|
200
|
+
input, select { width: 100%; box-sizing: border-box; background: #1e222d; color: #d1d4dc; border: 1px solid #363a45; border-radius: 4px; padding: 5px; }
|
|
201
|
+
input[type=checkbox] { width: auto; }
|
|
202
|
+
button { background: #2962ff; color: white; border: 0; border-radius: 4px; padding: 6px 10px; cursor: pointer; }
|
|
203
|
+
</style>
|
|
204
|
+
<script src="${library}"></script>
|
|
205
|
+
</head>
|
|
206
|
+
<body>
|
|
207
|
+
<div id="main">
|
|
208
|
+
<div id="head"><span id="title">${escapeHtml(name)}</span> <span id="status"></span></div>
|
|
209
|
+
<div id="msg"></div>
|
|
210
|
+
<div id="chart"></div>
|
|
211
|
+
</div>
|
|
212
|
+
<div id="side"><h3>Settings</h3><form id="form"></form><button id="reset" type="button">Default settings</button></div>
|
|
213
|
+
<script>
|
|
214
|
+
const LWC = window.LightweightCharts;
|
|
215
|
+
const values = {};
|
|
216
|
+
let chart = null;
|
|
217
|
+
const $ = (id) => document.getElementById(id);
|
|
218
|
+
function show(kind, text) { const m = $('msg'); m.className = text ? kind : ''; m.textContent = text || ''; }
|
|
219
|
+
const POS = { aboveBar: 'aboveBar', belowBar: 'belowBar', top: 'aboveBar', bottom: 'belowBar', absolute: 'inBar' };
|
|
220
|
+
const SHAPE = { triangleUp: 'arrowUp', arrowUp: 'arrowUp', labelUp: 'arrowUp', triangleDown: 'arrowDown', arrowDown: 'arrowDown', labelDown: 'arrowDown', square: 'square' };
|
|
221
|
+
function draw(data) {
|
|
222
|
+
if (!LWC) { show('error', 'lightweight-charts could not be loaded: install it (npm install lightweight-charts) or check the network.'); return; }
|
|
223
|
+
if (chart) chart.remove();
|
|
224
|
+
chart = LWC.createChart($('chart'), { autoSize: true, layout: { background: { color: '#131722' }, textColor: '#d1d4dc', panes: { separatorColor: '#2a2e39' } }, grid: { vertLines: { color: '#1e222d' }, horzLines: { color: '#1e222d' } }, timeScale: { timeVisible: false } });
|
|
225
|
+
const barColors = new Map(((data.result && data.result.barColors) || []).map((b) => [b.time, b.color]));
|
|
226
|
+
const candles = chart.addSeries(LWC.CandlestickSeries, { upColor: '#26a69a', downColor: '#ef5350', borderVisible: false, wickUpColor: '#26a69a', wickDownColor: '#ef5350' }, 0);
|
|
227
|
+
candles.setData(data.bars.map((b) => { const c = barColors.get(b.time); return c ? { time: b.time, open: b.open, high: b.high, low: b.low, close: b.close, color: c, wickColor: c } : { time: b.time, open: b.open, high: b.high, low: b.low, close: b.close }; }));
|
|
228
|
+
if (!data.ok) return;
|
|
229
|
+
const pane = data.metadata.overlay ? 0 : 1;
|
|
230
|
+
let first = null;
|
|
231
|
+
for (const p of data.plotConfig) {
|
|
232
|
+
const points = (data.result.plots[p.id] || []);
|
|
233
|
+
const style = p.style || 'line';
|
|
234
|
+
const Kind = style === 'histogram' || style === 'columns' ? LWC.HistogramSeries : style === 'area' ? LWC.AreaSeries : LWC.LineSeries;
|
|
235
|
+
const opts = { color: p.color, lineWidth: p.lineWidth || 1, title: p.title, priceLineVisible: false, lastValueVisible: true };
|
|
236
|
+
// the levels (price lines) count in the scale of the pane
|
|
237
|
+
const levels = (data.hlineConfig || []).map((h) => h.price).filter((x) => Number.isFinite(x));
|
|
238
|
+
if (pane === 1 && levels.length) opts.autoscaleInfoProvider = (original) => {
|
|
239
|
+
const r = original();
|
|
240
|
+
if (!r || !r.priceRange) return r;
|
|
241
|
+
return { ...r, priceRange: { minValue: Math.min(r.priceRange.minValue, ...levels), maxValue: Math.max(r.priceRange.maxValue, ...levels) } };
|
|
242
|
+
};
|
|
243
|
+
if (style === 'circles' || style === 'cross') Object.assign(opts, { lineVisible: false, pointMarkersVisible: true });
|
|
244
|
+
if (style === 'stepline') opts.lineType = 1;
|
|
245
|
+
if (Kind === LWC.AreaSeries) Object.assign(opts, { lineColor: p.color, topColor: p.color + '55', bottomColor: p.color + '05' });
|
|
246
|
+
const s = chart.addSeries(Kind, opts, pane);
|
|
247
|
+
s.setData(points.map((x) => (x.color ? { time: x.time, value: x.value, color: x.color } : { time: x.time, value: x.value })));
|
|
248
|
+
first = first || s;
|
|
249
|
+
}
|
|
250
|
+
const host = pane === 0 ? candles : first;
|
|
251
|
+
if (host) for (const h of data.hlineConfig || []) host.createPriceLine({ price: h.price, color: h.color || '#787b86', lineStyle: h.linestyle === 'solid' ? 0 : h.linestyle === 'dotted' ? 1 : 2, lineWidth: h.linewidth || 1, title: h.title || '' });
|
|
252
|
+
const markers = (data.result.markers || []).map((m) => ({ time: m.time, position: POS[m.position] || 'aboveBar', shape: SHAPE[m.shape] || 'circle', color: m.color || '#2962ff', text: m.text || '' }));
|
|
253
|
+
for (const l of data.result.labels || []) if (l.time !== undefined) markers.push({ time: l.time, position: 'aboveBar', shape: 'circle', color: l.color || '#2962ff', text: l.text || '' });
|
|
254
|
+
if (markers.length && LWC.createSeriesMarkers) LWC.createSeriesMarkers(pane === 0 || !first ? candles : first, markers.sort((a, b) => a.time - b.time));
|
|
255
|
+
const bg = data.result.bgColors || [];
|
|
256
|
+
if (bg.length) {
|
|
257
|
+
const s = chart.addSeries(LWC.HistogramSeries, { priceScaleId: 'bg', priceLineVisible: false, lastValueVisible: false }, pane);
|
|
258
|
+
s.priceScale().applyOptions({ scaleMargins: { top: 0, bottom: 0 }, visible: false });
|
|
259
|
+
s.setData(bg.map((b) => ({ time: b.time, value: 1, color: b.color })));
|
|
260
|
+
}
|
|
261
|
+
if (pane === 1 && chart.panes().length > 1) chart.panes()[1].setHeight(Math.round($('chart').clientHeight * 0.3));
|
|
262
|
+
}
|
|
263
|
+
function form(config) {
|
|
264
|
+
const f = $('form');
|
|
265
|
+
f.innerHTML = '';
|
|
266
|
+
for (const c of config || []) {
|
|
267
|
+
const l = document.createElement('label');
|
|
268
|
+
const t = document.createElement('span');
|
|
269
|
+
t.textContent = c.title || c.id;
|
|
270
|
+
l.appendChild(t);
|
|
271
|
+
let el;
|
|
272
|
+
const value = c.id in values ? values[c.id] : c.defval;
|
|
273
|
+
if (c.options) { el = document.createElement('select'); for (const o of c.options) { const op = document.createElement('option'); op.value = String(o); op.textContent = (c.optionsTitles && c.optionsTitles[o]) || String(o); el.appendChild(op); } el.value = String(value); }
|
|
274
|
+
else if (c.type === 'bool') { el = document.createElement('input'); el.type = 'checkbox'; el.checked = Boolean(value); }
|
|
275
|
+
else if (c.type === 'color') { el = document.createElement('input'); el.type = 'color'; el.value = String(value).slice(0, 7); }
|
|
276
|
+
else { el = document.createElement('input'); el.type = ['int', 'float', 'price'].includes(c.type) ? 'number' : 'text'; if (c.min !== undefined) el.min = c.min; if (c.max !== undefined) el.max = c.max; if (c.step !== undefined) el.step = c.step; el.value = String(value); }
|
|
277
|
+
el.onchange = () => {
|
|
278
|
+
let v = el.type === 'checkbox' ? el.checked : el.value;
|
|
279
|
+
if (['int', 'float', 'price'].includes(c.type)) v = Number(v);
|
|
280
|
+
if (c.options && typeof c.defval === 'number') v = Number(v);
|
|
281
|
+
values[c.id] = v;
|
|
282
|
+
load();
|
|
283
|
+
};
|
|
284
|
+
l.appendChild(el);
|
|
285
|
+
f.appendChild(l);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
async function load() {
|
|
289
|
+
$('status').textContent = '…';
|
|
290
|
+
const r = await fetch('/run?inputs=' + encodeURIComponent(JSON.stringify(values)));
|
|
291
|
+
const data = await r.json();
|
|
292
|
+
$('status').textContent = data.ok ? '' : '(error)';
|
|
293
|
+
if (data.ok) { $('title').textContent = data.metadata.title; form(data.inputConfig); show(data.warnings.length ? 'warn' : '', data.warnings.join('\\n')); }
|
|
294
|
+
else show('error', data.error);
|
|
295
|
+
draw(data);
|
|
296
|
+
}
|
|
297
|
+
$('reset').onclick = () => { for (const k of Object.keys(values)) delete values[k]; load(); };
|
|
298
|
+
new EventSource('/events').onmessage = () => load();
|
|
299
|
+
load();
|
|
300
|
+
</script>
|
|
301
|
+
</body>
|
|
302
|
+
</html>`;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function escapeHtml(s: string): string {
|
|
306
|
+
return s.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]!);
|
|
307
|
+
}
|
package/src/color/index.ts
CHANGED
|
@@ -45,7 +45,7 @@ const alphaOf = (transp: number): float =>
|
|
|
45
45
|
* transparent
|
|
46
46
|
*
|
|
47
47
|
* @example
|
|
48
|
-
* ```
|
|
48
|
+
* ```js
|
|
49
49
|
* color.rgb(255, 0, 0) // Returns: "rgb(255, 0, 0)" - Red
|
|
50
50
|
* color.rgb(0, 255, 0, 50) // Returns: "rgba(0, 255, 0, 0.5)" - Semi-transparent green
|
|
51
51
|
* color.rgb(300, 0, 0) // Returns: "rgb(255, 0, 0)" - Clamped to 255
|
|
@@ -77,7 +77,7 @@ export function rgb(red: simple_int, green: simple_int, blue: simple_int, transp
|
|
|
77
77
|
* - Format: RRGGBB where each component is 00-FF
|
|
78
78
|
*
|
|
79
79
|
* @example
|
|
80
|
-
* ```
|
|
80
|
+
* ```js
|
|
81
81
|
* color.from_hex("#FF0000") // Returns: "rgb(255, 0, 0)" - Red
|
|
82
82
|
* color.from_hex("00FF00", 50) // Returns: "rgba(0, 255, 0, 0.5)" - Semi-transparent green
|
|
83
83
|
* color.from_hex("#0000FF") // Returns: "rgb(0, 0, 255)" - Blue
|
|
@@ -113,7 +113,7 @@ export function from_hex(hex: string, transp?: simple_float): string {
|
|
|
113
113
|
* `color.new(color(na), 30)` is computed at compile time and stays na; a JS function cannot tell the two apart.
|
|
114
114
|
*
|
|
115
115
|
* @example
|
|
116
|
-
* ```
|
|
116
|
+
* ```js
|
|
117
117
|
* const red = color.rgb(255, 0, 0)
|
|
118
118
|
* color.new_color(red, 50) // Returns: "rgba(255, 0, 0, 0.5)" - Semi-transparent red
|
|
119
119
|
* color.new_color(red, 0) // Returns: "rgb(255, 0, 0)" - Fully opaque
|
|
@@ -153,7 +153,7 @@ const NEW_COLORS_KEPT = 1024;
|
|
|
153
153
|
* @returns Red component value (0-255)
|
|
154
154
|
*
|
|
155
155
|
* @example
|
|
156
|
-
* ```
|
|
156
|
+
* ```js
|
|
157
157
|
* color.r(color.rgb(255, 128, 64)) // Returns: 255
|
|
158
158
|
* color.r(color.from_hex("#FF0000")) // Returns: 255
|
|
159
159
|
* color.r(color.from_hex("#FFA500")) // Returns: 255 (orange)
|
|
@@ -170,7 +170,7 @@ export function r(clr: color): int {
|
|
|
170
170
|
* @returns Green component value (0-255)
|
|
171
171
|
*
|
|
172
172
|
* @example
|
|
173
|
-
* ```
|
|
173
|
+
* ```js
|
|
174
174
|
* color.g(color.rgb(255, 128, 64)) // Returns: 128
|
|
175
175
|
* color.g(color.from_hex("#00FF00")) // Returns: 255
|
|
176
176
|
* color.g(color.from_hex("#FFA500")) // Returns: 165 (orange)
|
|
@@ -187,7 +187,7 @@ export function g(clr: color): int {
|
|
|
187
187
|
* @returns Blue component value (0-255)
|
|
188
188
|
*
|
|
189
189
|
* @example
|
|
190
|
-
* ```
|
|
190
|
+
* ```js
|
|
191
191
|
* color.b(color.rgb(255, 128, 64)) // Returns: 64
|
|
192
192
|
* color.b(color.from_hex("#0000FF")) // Returns: 255
|
|
193
193
|
* color.b(color.from_hex("#FFA500")) // Returns: 0 (orange)
|
|
@@ -211,7 +211,7 @@ export function b(clr: color): int {
|
|
|
211
211
|
* - an `na` colour (null / undefined) is fully transparent: 100
|
|
212
212
|
*
|
|
213
213
|
* @example
|
|
214
|
-
* ```
|
|
214
|
+
* ```js
|
|
215
215
|
* color.t(color.rgb(255, 0, 0)) // Returns: 0 (opaque)
|
|
216
216
|
* color.t(color.rgb(255, 0, 0, 50)) // Returns: 50
|
|
217
217
|
* color.t(color.rgb(255, 0, 0, 100)) // Returns: 100 (fully transparent)
|
|
@@ -348,7 +348,7 @@ export const yellow = '#FDD835';
|
|
|
348
348
|
* - Works with rgb(), rgba() and hex (#RRGGBB, #RRGGBBAA) colours
|
|
349
349
|
*
|
|
350
350
|
* @example
|
|
351
|
-
* ```
|
|
351
|
+
* ```js
|
|
352
352
|
* // Value at middle of range gets middle color
|
|
353
353
|
* const midColor = color.from_gradient(50, 0, 100,
|
|
354
354
|
* color.rgb(255, 0, 0), // Red at bottom
|
|
@@ -356,8 +356,8 @@ export const yellow = '#FDD835';
|
|
|
356
356
|
* ); // Returns color between red and green
|
|
357
357
|
*
|
|
358
358
|
* // Value at extremes
|
|
359
|
-
* const lowColor = color.from_gradient(-10, 0, 100, red, green); //
|
|
360
|
-
* const highColor = color.from_gradient(150, 0, 100, red, green); //
|
|
359
|
+
* const lowColor = color.from_gradient(-10, 0, 100, color.red, color.green); // red: at or below the bottom
|
|
360
|
+
* const highColor = color.from_gradient(150, 0, 100, color.red, color.green); // green: at or above the top
|
|
361
361
|
* ```
|
|
362
362
|
*/
|
|
363
363
|
export function from_gradient(
|
|
@@ -411,7 +411,7 @@ export function from_gradient(
|
|
|
411
411
|
* This is an alias for `new_color()` to match PineScript's `color.new()` syntax.
|
|
412
412
|
*
|
|
413
413
|
* @example
|
|
414
|
-
* ```
|
|
414
|
+
* ```js
|
|
415
415
|
* const redColor = color.rgb(255, 0, 0);
|
|
416
416
|
* const transparentRed = color.new(redColor, 50); // 50% transparent red
|
|
417
417
|
* ```
|
package/src/color/parse.ts
CHANGED
|
@@ -55,6 +55,13 @@ function parseText(clr: string): ParsedColor {
|
|
|
55
55
|
return BLACK;
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
+
/** The text is a colour {@link parseColor} reads (hex or rgb() / rgba()), not one it takes for opaque black. */
|
|
59
|
+
export function isColorText(clr: unknown): boolean {
|
|
60
|
+
if (typeof clr !== 'string') return false;
|
|
61
|
+
const s = clr.trim();
|
|
62
|
+
return /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(s) || /^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*[\d.]+\s*)?\)$/i.test(s);
|
|
63
|
+
}
|
|
64
|
+
|
|
58
65
|
/** Alpha byte (0-255) of an alpha (0-1), as PineScript stores it. */
|
|
59
66
|
export const alphaByte = (a: float): int => Math.round(a * 255);
|
|
60
67
|
|
package/src/compare/index.ts
CHANGED
|
@@ -1,46 +1,110 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Comparisons of two numbers with a small tolerance (`compare.eq`, `compare.lt`...), for the plain numbers of a bar
|
|
3
|
+
* loop. JavaScript's `==`, `<`... compare exactly: `0.1 + 0.2 === 0.3` is false.
|
|
3
4
|
*
|
|
4
|
-
*
|
|
5
|
-
* -
|
|
6
|
-
*
|
|
7
|
-
* - every comparison with an
|
|
5
|
+
* Rules:
|
|
6
|
+
* - an absolute tolerance of 1e-10: `a` equals `b` when `|a - b| <= 1e-10`, `a < b` when `b - a > 1e-10` (the same
|
|
7
|
+
* for every magnitude; `compare.eq(0.1 + 0.2, 0.3)` is true)
|
|
8
|
+
* - every comparison with an na (NaN) operand is false, `compare.ne` included
|
|
8
9
|
* - built-in functions (`ta.crossover`, `ta.pivothigh`, `ta.highestbars`...) compare exactly
|
|
9
10
|
*
|
|
10
11
|
* The `Series` comparison methods (`gt`, `gte`, `lt`, `lte`, `eq`, `neq`) follow the same rules.
|
|
11
12
|
*/
|
|
12
13
|
|
|
13
|
-
/** Tolerance of
|
|
14
|
+
/** Tolerance of the comparisons: two numbers closer than 1e-10 are equal. */
|
|
14
15
|
export const EPSILON = 1e-10;
|
|
15
16
|
|
|
16
17
|
const valid = (a: number, b: number): boolean => !Number.isNaN(a) && !Number.isNaN(b);
|
|
17
18
|
|
|
18
|
-
/**
|
|
19
|
+
/**
|
|
20
|
+
* Tests whether two numbers are equal, within a tolerance of 1e-10.
|
|
21
|
+
* False when either number is na (NaN).
|
|
22
|
+
* @param a - The first number.
|
|
23
|
+
* @param b - The second number.
|
|
24
|
+
* @returns True when `|a - b| <= 1e-10`.
|
|
25
|
+
* @example
|
|
26
|
+
* ```js
|
|
27
|
+
* eachBar((c) => {
|
|
28
|
+
* if (compare.eq(c.close, c.open)) label.new(c.i, c.high, "Doji");
|
|
29
|
+
* });
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
19
32
|
export function eq(a: number, b: number): boolean {
|
|
20
33
|
return valid(a, b) && Math.abs(a - b) <= EPSILON;
|
|
21
34
|
}
|
|
22
35
|
|
|
23
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* Tests whether two numbers differ by more than 1e-10.
|
|
38
|
+
* False when either number is na (NaN), unlike JavaScript's `!==`.
|
|
39
|
+
* @param a - The first number.
|
|
40
|
+
* @param b - The second number.
|
|
41
|
+
* @returns True when `|a - b| > 1e-10`.
|
|
42
|
+
* @example
|
|
43
|
+
* ```js
|
|
44
|
+
* const moved = eachBar((c) => (compare.ne(c.close, c.get(close, 1)) ? 1 : 0));
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
24
47
|
export function ne(a: number, b: number): boolean {
|
|
25
48
|
return valid(a, b) && Math.abs(a - b) > EPSILON;
|
|
26
49
|
}
|
|
27
50
|
|
|
28
|
-
/**
|
|
51
|
+
/**
|
|
52
|
+
* Tests whether `a` is less than `b` by more than 1e-10.
|
|
53
|
+
* False when either number is na (NaN).
|
|
54
|
+
* @param a - The first number.
|
|
55
|
+
* @param b - The second number.
|
|
56
|
+
* @returns True when `b - a > 1e-10`.
|
|
57
|
+
* @example
|
|
58
|
+
* ```js
|
|
59
|
+
* const below = eachBar((c) => (compare.lt(c.close, c.open) ? 1 : 0));
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
29
62
|
export function lt(a: number, b: number): boolean {
|
|
30
63
|
return valid(a, b) && b - a > EPSILON;
|
|
31
64
|
}
|
|
32
65
|
|
|
33
|
-
/**
|
|
66
|
+
/**
|
|
67
|
+
* Tests whether `a` is less than or equal to `b`, within a tolerance of 1e-10.
|
|
68
|
+
* False when either number is na (NaN).
|
|
69
|
+
* @param a - The first number.
|
|
70
|
+
* @param b - The second number.
|
|
71
|
+
* @returns True when `a - b <= 1e-10`.
|
|
72
|
+
* @example
|
|
73
|
+
* ```js
|
|
74
|
+
* const notAbove = eachBar((c) => (compare.le(c.close, c.open) ? 1 : 0));
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
34
77
|
export function le(a: number, b: number): boolean {
|
|
35
78
|
return valid(a, b) && a - b <= EPSILON;
|
|
36
79
|
}
|
|
37
80
|
|
|
38
|
-
/**
|
|
81
|
+
/**
|
|
82
|
+
* Tests whether `a` is greater than `b` by more than 1e-10.
|
|
83
|
+
* False when either number is na (NaN).
|
|
84
|
+
* @param a - The first number.
|
|
85
|
+
* @param b - The second number.
|
|
86
|
+
* @returns True when `a - b > 1e-10`.
|
|
87
|
+
* @example
|
|
88
|
+
* ```js
|
|
89
|
+
* const ma = ta.sma(close, 20);
|
|
90
|
+
* const above = eachBar((c) => (compare.gt(c.close, c.get(ma)) ? 1 : 0));
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
39
93
|
export function gt(a: number, b: number): boolean {
|
|
40
94
|
return valid(a, b) && a - b > EPSILON;
|
|
41
95
|
}
|
|
42
96
|
|
|
43
|
-
/**
|
|
97
|
+
/**
|
|
98
|
+
* Tests whether `a` is greater than or equal to `b`, within a tolerance of 1e-10.
|
|
99
|
+
* False when either number is na (NaN).
|
|
100
|
+
* @param a - The first number.
|
|
101
|
+
* @param b - The second number.
|
|
102
|
+
* @returns True when `b - a <= 1e-10`.
|
|
103
|
+
* @example
|
|
104
|
+
* ```js
|
|
105
|
+
* const notBelow = eachBar((c) => (compare.ge(c.close, c.open) ? 1 : 0));
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
44
108
|
export function ge(a: number, b: number): boolean {
|
|
45
109
|
return valid(a, b) && b - a <= EPSILON;
|
|
46
110
|
}
|
package/src/drawing/registry.ts
CHANGED
|
@@ -273,8 +273,17 @@ let pending: Record<CountedKind, number> = { line: 0, label: 0, box: 0, polyline
|
|
|
273
273
|
const PENDING_RESET: Record<CountedKind, number> = { line: 5, label: 5, box: 5, polyline: 3 };
|
|
274
274
|
|
|
275
275
|
/**
|
|
276
|
-
* Marks
|
|
277
|
-
*
|
|
276
|
+
* Marks a drawing as held, so the `max_*_count` limit of the script never deletes it (it still counts towards the
|
|
277
|
+
* limit). Each call adds one hold; {@link releaseDrawing} removes one. Most scripts use `varDrawing()` instead, which
|
|
278
|
+
* holds and releases for them.
|
|
279
|
+
* @param obj - The drawing to hold (a line, label, box, polyline, linefill or table).
|
|
280
|
+
* @returns The same object, so the call can wrap a `*.new()` call.
|
|
281
|
+
* @example
|
|
282
|
+
* ```js
|
|
283
|
+
* eachBar((c) => {
|
|
284
|
+
* if (c.i === 0) holdDrawing(label.new(c.i, c.high, "First bar"));
|
|
285
|
+
* });
|
|
286
|
+
* ```
|
|
278
287
|
*/
|
|
279
288
|
export function holdDrawing<T extends object>(obj: T): T {
|
|
280
289
|
const record = Held.get(obj) ?? Held.create(obj);
|
|
@@ -283,7 +292,18 @@ export function holdDrawing<T extends object>(obj: T): T {
|
|
|
283
292
|
return obj;
|
|
284
293
|
}
|
|
285
294
|
|
|
286
|
-
/**
|
|
295
|
+
/**
|
|
296
|
+
* Removes one hold made by {@link holdDrawing}: once no hold is left, the `max_*_count` limit can delete the drawing
|
|
297
|
+
* again. Does nothing for na or an object that is not held.
|
|
298
|
+
* @param obj - The held drawing, or `null` / `undefined` (nothing to release).
|
|
299
|
+
* @example
|
|
300
|
+
* ```js
|
|
301
|
+
* let kept;
|
|
302
|
+
* eachBar((c) => {
|
|
303
|
+
* if (c.i % 50 === 0) { releaseDrawing(kept); kept = holdDrawing(label.new(c.i, c.high, "Mark")); }
|
|
304
|
+
* });
|
|
305
|
+
* ```
|
|
306
|
+
*/
|
|
287
307
|
export function releaseDrawing(obj: object | null | undefined): void {
|
|
288
308
|
if (!obj) return;
|
|
289
309
|
const record = Held.get(obj);
|
|
@@ -321,9 +341,9 @@ function fillProtected(obj: object): boolean {
|
|
|
321
341
|
return bar !== undefined && currentBar !== null && currentBar - bar < LINEFILL_RELEASE_BARS;
|
|
322
342
|
}
|
|
323
343
|
|
|
324
|
-
/** A
|
|
344
|
+
/** A variable that holds one drawing from bar to bar, made by `varDrawing()`. */
|
|
325
345
|
export interface DrawingVariable<T extends object> {
|
|
326
|
-
/** The
|
|
346
|
+
/** The held drawing (`undefined`: none); setting it holds the new object and releases the one before. */
|
|
327
347
|
value: T | undefined;
|
|
328
348
|
}
|
|
329
349
|
|
|
@@ -526,6 +546,18 @@ function cutOldest<K extends DrawingKind>(
|
|
|
526
546
|
/** Kinds of the objects created since the last reset (a table counts too), in no order. */
|
|
527
547
|
const created = new Set<DrawingKind>();
|
|
528
548
|
|
|
549
|
+
/** Objects deleted because their kind was over its maximum count, by kind, since the last reset. */
|
|
550
|
+
let dropped: Partial<Record<DrawingKind, number>> = {};
|
|
551
|
+
|
|
552
|
+
/** The objects deleted since the last {@link resetDrawings} because their kind was over its maximum count, by kind. */
|
|
553
|
+
export function droppedDrawings(): Partial<Record<DrawingKind, number>> {
|
|
554
|
+
return { ...dropped };
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
function countDropped(kind: DrawingKind, n: number): void {
|
|
558
|
+
if (n > 0) dropped[kind] = (dropped[kind] ?? 0) + n;
|
|
559
|
+
}
|
|
560
|
+
|
|
529
561
|
/** The kinds of drawing objects created since the last {@link resetDrawings}, even when none is alive any more. */
|
|
530
562
|
export function createdDrawingKinds(): DrawingKind[] {
|
|
531
563
|
return [...created];
|
|
@@ -552,6 +584,7 @@ export function register<K extends DrawingKind>(kind: K, obj: DrawingTypes[K]):
|
|
|
552
584
|
list.push(obj);
|
|
553
585
|
if (kind === 'linefill') trackFill(obj as Linefill);
|
|
554
586
|
const cut = cutOldest(kind, list, obj);
|
|
587
|
+
countDropped(kind, cut.length);
|
|
555
588
|
if (kind === 'polyline') pending.polyline += cut.length;
|
|
556
589
|
for (const old of cut) {
|
|
557
590
|
if (kind === 'linefill') untrackFill(old as Linefill);
|
|
@@ -578,6 +611,7 @@ function registerLast<K extends DrawingKind>(bar: LastBar, kind: K, obj: Drawing
|
|
|
578
611
|
if (oldCandidate) {
|
|
579
612
|
// the objects of the bars before only; a line takes its linefills with it
|
|
580
613
|
const cut = cutOldest(kind, list, obj, isOld);
|
|
614
|
+
countDropped(kind, cut.length);
|
|
581
615
|
if (kind === 'polyline') {
|
|
582
616
|
pending.polyline += cut.length;
|
|
583
617
|
bar.oldPolylinesGone += cut.length;
|
|
@@ -587,6 +621,7 @@ function registerLast<K extends DrawingKind>(bar: LastBar, kind: K, obj: Drawing
|
|
|
587
621
|
// the polylines of the bars before deleted on this bar count before the cut (#176)
|
|
588
622
|
if (kind === 'polyline' && pending.polyline < bar.oldPolylinesGone) pending.polyline = bar.oldPolylinesGone;
|
|
589
623
|
const cut = cutOldest(kind, list, obj);
|
|
624
|
+
countDropped(kind, cut.length);
|
|
590
625
|
if (kind === 'polyline' && cut.length > 0) pending.polyline = bar.oldPolylinesGone;
|
|
591
626
|
for (const old of cut) markDeleted(kind, old, false);
|
|
592
627
|
}
|
|
@@ -626,6 +661,7 @@ export function resetDrawings(newLimits: DrawingLimits = {}): void {
|
|
|
626
661
|
for (const kind of Object.keys(live) as DrawingKind[]) live[kind].replace([]);
|
|
627
662
|
fillsOfLine = new Map();
|
|
628
663
|
created.clear();
|
|
664
|
+
dropped = {};
|
|
629
665
|
holds = { others: new WeakMap(), records: 0, variables: [] };
|
|
630
666
|
pending = { line: 0, label: 0, box: 0, polyline: 0 };
|
|
631
667
|
currentBar = null;
|
|
@@ -648,6 +684,7 @@ export function setDrawingLimits(newLimits: DrawingLimits): void {
|
|
|
648
684
|
export interface DrawingState {
|
|
649
685
|
live: { [K in DrawingKind]: Array<DrawingTypes[K]> };
|
|
650
686
|
created: DrawingKind[];
|
|
687
|
+
dropped: Partial<Record<DrawingKind, number>>;
|
|
651
688
|
holds: Holds;
|
|
652
689
|
pending: Record<CountedKind, number>;
|
|
653
690
|
currentBar: number | null;
|
|
@@ -668,6 +705,7 @@ export function saveDrawingState(): DrawingState {
|
|
|
668
705
|
table: live.table.toArray(),
|
|
669
706
|
},
|
|
670
707
|
created: [...created],
|
|
708
|
+
dropped: { ...dropped },
|
|
671
709
|
holds,
|
|
672
710
|
pending: { ...pending },
|
|
673
711
|
currentBar,
|
|
@@ -796,6 +834,7 @@ export function restoreDrawingState(s: DrawingState): void {
|
|
|
796
834
|
for (const fill of s.live.linefill) trackFill(fill);
|
|
797
835
|
created.clear();
|
|
798
836
|
for (const kind of s.created) created.add(kind);
|
|
837
|
+
dropped = { ...s.dropped };
|
|
799
838
|
holds = s.holds;
|
|
800
839
|
pending = { ...s.pending };
|
|
801
840
|
currentBar = s.currentBar;
|