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.
Files changed (300) hide show
  1. package/README.md +25 -1
  2. package/bin/oakscript.mjs +10 -3
  3. package/dist/cjs/box/index.d.ts +348 -289
  4. package/dist/cjs/box/index.d.ts.map +1 -1
  5. package/dist/cjs/box/index.js.map +2 -2
  6. package/dist/cjs/check/node.d.ts.map +1 -1
  7. package/dist/cjs/check/node.js +1 -0
  8. package/dist/cjs/check/node.js.map +2 -2
  9. package/dist/cjs/check/preview.d.ts +31 -0
  10. package/dist/cjs/check/preview.d.ts.map +1 -0
  11. package/dist/cjs/check/preview.js +303 -0
  12. package/dist/cjs/check/preview.js.map +7 -0
  13. package/dist/cjs/color/index.d.ts +11 -11
  14. package/dist/cjs/color/index.js.map +1 -1
  15. package/dist/cjs/color/parse.d.ts +2 -0
  16. package/dist/cjs/color/parse.d.ts.map +1 -1
  17. package/dist/cjs/color/parse.js +6 -0
  18. package/dist/cjs/color/parse.js.map +2 -2
  19. package/dist/cjs/compare/index.d.ts +76 -12
  20. package/dist/cjs/compare/index.d.ts.map +1 -1
  21. package/dist/cjs/compare/index.js.map +2 -2
  22. package/dist/cjs/drawing/registry.d.ts +28 -5
  23. package/dist/cjs/drawing/registry.d.ts.map +1 -1
  24. package/dist/cjs/drawing/registry.js +14 -0
  25. package/dist/cjs/drawing/registry.js.map +2 -2
  26. package/dist/cjs/index.d.ts +1 -1
  27. package/dist/cjs/index.js +1 -1
  28. package/dist/cjs/index.js.map +1 -1
  29. package/dist/cjs/label/index.d.ts +265 -187
  30. package/dist/cjs/label/index.d.ts.map +1 -1
  31. package/dist/cjs/label/index.js +1 -1
  32. package/dist/cjs/label/index.js.map +2 -2
  33. package/dist/cjs/line/index.d.ts +247 -207
  34. package/dist/cjs/line/index.d.ts.map +1 -1
  35. package/dist/cjs/line/index.js.map +2 -2
  36. package/dist/cjs/linefill/index.d.ts +61 -89
  37. package/dist/cjs/linefill/index.d.ts.map +1 -1
  38. package/dist/cjs/linefill/index.js.map +2 -2
  39. package/dist/cjs/math/index.d.ts +49 -40
  40. package/dist/cjs/math/index.d.ts.map +1 -1
  41. package/dist/cjs/math/index.js.map +2 -2
  42. package/dist/cjs/polyline/index.d.ts +57 -78
  43. package/dist/cjs/polyline/index.d.ts.map +1 -1
  44. package/dist/cjs/polyline/index.js.map +2 -2
  45. package/dist/cjs/runtime/input-active.d.ts +2 -2
  46. package/dist/cjs/runtime/input-active.js.map +1 -1
  47. package/dist/cjs/runtime/series.d.ts +241 -161
  48. package/dist/cjs/runtime/series.d.ts.map +1 -1
  49. package/dist/cjs/runtime/series.js +223 -127
  50. package/dist/cjs/runtime/series.js.map +2 -2
  51. package/dist/cjs/script/api/alert.d.ts +37 -0
  52. package/dist/cjs/script/api/alert.d.ts.map +1 -0
  53. package/dist/cjs/script/api/alert.js +17 -0
  54. package/dist/cjs/script/api/alert.js.map +7 -0
  55. package/dist/cjs/script/api/calc.d.ts +232 -0
  56. package/dist/cjs/script/api/calc.d.ts.map +1 -0
  57. package/dist/cjs/script/api/calc.js +17 -0
  58. package/dist/cjs/script/api/calc.js.map +7 -0
  59. package/dist/cjs/script/api/color.d.ts +213 -0
  60. package/dist/cjs/script/api/color.d.ts.map +1 -0
  61. package/dist/cjs/script/api/color.js +17 -0
  62. package/dist/cjs/script/api/color.js.map +7 -0
  63. package/dist/cjs/script/api/context.d.ts +764 -0
  64. package/dist/cjs/script/api/context.d.ts.map +1 -0
  65. package/dist/cjs/script/api/context.js +17 -0
  66. package/dist/cjs/script/api/context.js.map +7 -0
  67. package/dist/cjs/script/api/log.d.ts +58 -0
  68. package/dist/cjs/script/api/log.d.ts.map +1 -0
  69. package/dist/cjs/script/api/log.js +17 -0
  70. package/dist/cjs/script/api/log.js.map +7 -0
  71. package/dist/cjs/script/api/strategy.d.ts +391 -0
  72. package/dist/cjs/script/api/strategy.d.ts.map +1 -0
  73. package/dist/cjs/script/api/strategy.js +17 -0
  74. package/dist/cjs/script/api/strategy.js.map +7 -0
  75. package/dist/cjs/script/api/ta.d.ts +1012 -0
  76. package/dist/cjs/script/api/ta.d.ts.map +1 -0
  77. package/dist/cjs/script/api/ta.js +17 -0
  78. package/dist/cjs/script/api/ta.js.map +7 -0
  79. package/dist/cjs/script/api/table.d.ts +479 -0
  80. package/dist/cjs/script/api/table.d.ts.map +1 -0
  81. package/dist/cjs/script/api/table.js +17 -0
  82. package/dist/cjs/script/api/table.js.map +7 -0
  83. package/dist/cjs/script/constants.d.ts +228 -83
  84. package/dist/cjs/script/constants.d.ts.map +1 -1
  85. package/dist/cjs/script/constants.js +87 -0
  86. package/dist/cjs/script/constants.js.map +2 -2
  87. package/dist/cjs/script/define.d.ts +94 -0
  88. package/dist/cjs/script/define.d.ts.map +1 -0
  89. package/dist/cjs/script/define.js +127 -0
  90. package/dist/cjs/script/define.js.map +7 -0
  91. package/dist/cjs/script/drawing-args.d.ts.map +1 -1
  92. package/dist/cjs/script/drawing-args.js +1 -1
  93. package/dist/cjs/script/drawing-args.js.map +2 -2
  94. package/dist/cjs/script/formula.d.ts +53 -0
  95. package/dist/cjs/script/formula.d.ts.map +1 -0
  96. package/dist/cjs/script/formula.js +402 -0
  97. package/dist/cjs/script/formula.js.map +7 -0
  98. package/dist/cjs/script/globals.d.ts +10 -0
  99. package/dist/cjs/script/globals.d.ts.map +1 -1
  100. package/dist/cjs/script/globals.js.map +1 -1
  101. package/dist/cjs/script/index.d.ts +1065 -1006
  102. package/dist/cjs/script/index.d.ts.map +1 -1
  103. package/dist/cjs/script/index.js +530 -60
  104. package/dist/cjs/script/index.js.map +3 -3
  105. package/dist/cjs/script/json.d.ts +117 -0
  106. package/dist/cjs/script/json.d.ts.map +1 -0
  107. package/dist/cjs/script/json.js +321 -0
  108. package/dist/cjs/script/json.js.map +7 -0
  109. package/dist/cjs/str/index.d.ts +50 -75
  110. package/dist/cjs/str/index.d.ts.map +1 -1
  111. package/dist/cjs/str/index.js +2 -2
  112. package/dist/cjs/str/index.js.map +2 -2
  113. package/dist/cjs/strategy/index.d.ts +102 -1
  114. package/dist/cjs/strategy/index.d.ts.map +1 -1
  115. package/dist/cjs/strategy/index.js.map +2 -2
  116. package/dist/cjs/table/index.d.ts +330 -49
  117. package/dist/cjs/table/index.d.ts.map +1 -1
  118. package/dist/cjs/table/index.js +55 -27
  119. package/dist/cjs/table/index.js.map +2 -2
  120. package/dist/cjs/text/index.d.ts +12 -14
  121. package/dist/cjs/text/index.d.ts.map +1 -1
  122. package/dist/cjs/text/index.js.map +2 -2
  123. package/dist/cjs/types/index.d.ts +15 -8
  124. package/dist/cjs/types/index.d.ts.map +1 -1
  125. package/dist/cjs/types/index.js +12 -3
  126. package/dist/cjs/types/index.js.map +2 -2
  127. package/dist/esm/box/index.d.ts +348 -289
  128. package/dist/esm/box/index.d.ts.map +1 -1
  129. package/dist/esm/box/index.js +276 -276
  130. package/dist/esm/box/index.js.map +1 -1
  131. package/dist/esm/check/node.d.ts.map +1 -1
  132. package/dist/esm/check/node.js +1 -0
  133. package/dist/esm/check/node.js.map +1 -1
  134. package/dist/esm/check/preview.d.ts +31 -0
  135. package/dist/esm/check/preview.d.ts.map +1 -0
  136. package/dist/esm/check/preview.js +296 -0
  137. package/dist/esm/check/preview.js.map +1 -0
  138. package/dist/esm/color/index.d.ts +11 -11
  139. package/dist/esm/color/index.js +11 -11
  140. package/dist/esm/color/parse.d.ts +2 -0
  141. package/dist/esm/color/parse.d.ts.map +1 -1
  142. package/dist/esm/color/parse.js +7 -0
  143. package/dist/esm/color/parse.js.map +1 -1
  144. package/dist/esm/compare/index.d.ts +76 -12
  145. package/dist/esm/compare/index.d.ts.map +1 -1
  146. package/dist/esm/compare/index.js +76 -12
  147. package/dist/esm/compare/index.js.map +1 -1
  148. package/dist/esm/drawing/registry.d.ts +28 -5
  149. package/dist/esm/drawing/registry.d.ts.map +1 -1
  150. package/dist/esm/drawing/registry.js +39 -3
  151. package/dist/esm/drawing/registry.js.map +1 -1
  152. package/dist/esm/index.d.ts +1 -1
  153. package/dist/esm/index.js +1 -1
  154. package/dist/esm/label/index.d.ts +265 -187
  155. package/dist/esm/label/index.d.ts.map +1 -1
  156. package/dist/esm/label/index.js +207 -177
  157. package/dist/esm/label/index.js.map +1 -1
  158. package/dist/esm/line/index.d.ts +247 -207
  159. package/dist/esm/line/index.d.ts.map +1 -1
  160. package/dist/esm/line/index.js +202 -194
  161. package/dist/esm/line/index.js.map +1 -1
  162. package/dist/esm/linefill/index.d.ts +61 -89
  163. package/dist/esm/linefill/index.d.ts.map +1 -1
  164. package/dist/esm/linefill/index.js +61 -89
  165. package/dist/esm/linefill/index.js.map +1 -1
  166. package/dist/esm/math/index.d.ts +49 -40
  167. package/dist/esm/math/index.d.ts.map +1 -1
  168. package/dist/esm/math/index.js +22 -9
  169. package/dist/esm/math/index.js.map +1 -1
  170. package/dist/esm/polyline/index.d.ts +57 -78
  171. package/dist/esm/polyline/index.d.ts.map +1 -1
  172. package/dist/esm/polyline/index.js +57 -78
  173. package/dist/esm/polyline/index.js.map +1 -1
  174. package/dist/esm/runtime/input-active.d.ts +2 -2
  175. package/dist/esm/runtime/input-active.js +2 -2
  176. package/dist/esm/runtime/series.d.ts +241 -161
  177. package/dist/esm/runtime/series.d.ts.map +1 -1
  178. package/dist/esm/runtime/series.js +241 -161
  179. package/dist/esm/runtime/series.js.map +1 -1
  180. package/dist/esm/script/api/alert.d.ts +37 -0
  181. package/dist/esm/script/api/alert.d.ts.map +1 -0
  182. package/dist/esm/script/api/alert.js +7 -0
  183. package/dist/esm/script/api/alert.js.map +1 -0
  184. package/dist/esm/script/api/calc.d.ts +232 -0
  185. package/dist/esm/script/api/calc.d.ts.map +1 -0
  186. package/dist/esm/script/api/calc.js +6 -0
  187. package/dist/esm/script/api/calc.js.map +1 -0
  188. package/dist/esm/script/api/color.d.ts +213 -0
  189. package/dist/esm/script/api/color.d.ts.map +1 -0
  190. package/dist/esm/script/api/color.js +6 -0
  191. package/dist/esm/script/api/color.js.map +1 -0
  192. package/dist/esm/script/api/context.d.ts +764 -0
  193. package/dist/esm/script/api/context.d.ts.map +1 -0
  194. package/dist/esm/script/api/context.js +7 -0
  195. package/dist/esm/script/api/context.js.map +1 -0
  196. package/dist/esm/script/api/log.d.ts +58 -0
  197. package/dist/esm/script/api/log.d.ts.map +1 -0
  198. package/dist/esm/script/api/log.js +6 -0
  199. package/dist/esm/script/api/log.js.map +1 -0
  200. package/dist/esm/script/api/strategy.d.ts +391 -0
  201. package/dist/esm/script/api/strategy.d.ts.map +1 -0
  202. package/dist/esm/script/api/strategy.js +7 -0
  203. package/dist/esm/script/api/strategy.js.map +1 -0
  204. package/dist/esm/script/api/ta.d.ts +1012 -0
  205. package/dist/esm/script/api/ta.d.ts.map +1 -0
  206. package/dist/esm/script/api/ta.js +6 -0
  207. package/dist/esm/script/api/ta.js.map +1 -0
  208. package/dist/esm/script/api/table.d.ts +479 -0
  209. package/dist/esm/script/api/table.d.ts.map +1 -0
  210. package/dist/esm/script/api/table.js +7 -0
  211. package/dist/esm/script/api/table.js.map +1 -0
  212. package/dist/esm/script/constants.d.ts +228 -83
  213. package/dist/esm/script/constants.d.ts.map +1 -1
  214. package/dist/esm/script/constants.js +110 -24
  215. package/dist/esm/script/constants.js.map +1 -1
  216. package/dist/esm/script/define.d.ts +94 -0
  217. package/dist/esm/script/define.d.ts.map +1 -0
  218. package/dist/esm/script/define.js +136 -0
  219. package/dist/esm/script/define.js.map +1 -0
  220. package/dist/esm/script/drawing-args.d.ts.map +1 -1
  221. package/dist/esm/script/drawing-args.js +2 -1
  222. package/dist/esm/script/drawing-args.js.map +1 -1
  223. package/dist/esm/script/formula.d.ts +53 -0
  224. package/dist/esm/script/formula.d.ts.map +1 -0
  225. package/dist/esm/script/formula.js +408 -0
  226. package/dist/esm/script/formula.js.map +1 -0
  227. package/dist/esm/script/globals.d.ts +10 -0
  228. package/dist/esm/script/globals.d.ts.map +1 -1
  229. package/dist/esm/script/globals.js.map +1 -1
  230. package/dist/esm/script/index.d.ts +1065 -1006
  231. package/dist/esm/script/index.d.ts.map +1 -1
  232. package/dist/esm/script/index.js +1096 -151
  233. package/dist/esm/script/index.js.map +1 -1
  234. package/dist/esm/script/json.d.ts +117 -0
  235. package/dist/esm/script/json.d.ts.map +1 -0
  236. package/dist/esm/script/json.js +375 -0
  237. package/dist/esm/script/json.js.map +1 -0
  238. package/dist/esm/str/index.d.ts +50 -75
  239. package/dist/esm/str/index.d.ts.map +1 -1
  240. package/dist/esm/str/index.js +51 -76
  241. package/dist/esm/str/index.js.map +1 -1
  242. package/dist/esm/strategy/index.d.ts +102 -1
  243. package/dist/esm/strategy/index.d.ts.map +1 -1
  244. package/dist/esm/strategy/index.js +1 -1
  245. package/dist/esm/strategy/index.js.map +1 -1
  246. package/dist/esm/table/index.d.ts +330 -49
  247. package/dist/esm/table/index.d.ts.map +1 -1
  248. package/dist/esm/table/index.js +372 -61
  249. package/dist/esm/table/index.js.map +1 -1
  250. package/dist/esm/text/index.d.ts +12 -14
  251. package/dist/esm/text/index.d.ts.map +1 -1
  252. package/dist/esm/text/index.js +12 -14
  253. package/dist/esm/text/index.js.map +1 -1
  254. package/dist/esm/types/index.d.ts +15 -8
  255. package/dist/esm/types/index.d.ts.map +1 -1
  256. package/dist/esm/types/index.js +15 -8
  257. package/dist/esm/types/index.js.map +1 -1
  258. package/docs/first-indicator.md +152 -0
  259. package/docs/guide.md +1185 -0
  260. package/docs/inventory.md +772 -0
  261. package/docs/no-code.md +207 -0
  262. package/docs/recipes.md +202 -0
  263. package/package.json +2 -1
  264. package/skills/oakscript/SKILL.md +8 -0
  265. package/skills/oakscript/reference/errors.md +3 -2
  266. package/src/box/index.ts +348 -289
  267. package/src/check/node.ts +1 -0
  268. package/src/check/preview.ts +307 -0
  269. package/src/color/index.ts +11 -11
  270. package/src/color/parse.ts +7 -0
  271. package/src/compare/index.ts +76 -12
  272. package/src/drawing/registry.ts +44 -5
  273. package/src/index.ts +1 -1
  274. package/src/label/index.ts +267 -189
  275. package/src/line/index.ts +248 -208
  276. package/src/linefill/index.ts +61 -89
  277. package/src/math/index.ts +51 -42
  278. package/src/polyline/index.ts +57 -78
  279. package/src/runtime/input-active.ts +2 -2
  280. package/src/runtime/series.ts +243 -163
  281. package/src/script/api/alert.ts +43 -0
  282. package/src/script/api/calc.ts +250 -0
  283. package/src/script/api/color.ts +245 -0
  284. package/src/script/api/context.ts +944 -0
  285. package/src/script/api/log.ts +60 -0
  286. package/src/script/api/strategy.ts +410 -0
  287. package/src/script/api/ta.ts +1115 -0
  288. package/src/script/api/table.ts +538 -0
  289. package/src/script/constants.ts +229 -25
  290. package/src/script/define.ts +221 -0
  291. package/src/script/drawing-args.ts +2 -1
  292. package/src/script/formula.ts +438 -0
  293. package/src/script/globals.ts +10 -0
  294. package/src/script/index.ts +1517 -239
  295. package/src/script/json.ts +457 -0
  296. package/src/str/index.ts +51 -76
  297. package/src/strategy/index.ts +102 -1
  298. package/src/table/index.ts +388 -62
  299. package/src/text/index.ts +12 -14
  300. 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) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!);
307
+ }
@@ -45,7 +45,7 @@ const alphaOf = (transp: number): float =>
45
45
  * transparent
46
46
  *
47
47
  * @example
48
- * ```typescript
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
- * ```typescript
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
- * ```typescript
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
- * ```typescript
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
- * ```typescript
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
- * ```typescript
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
- * ```typescript
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
- * ```typescript
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); // Returns red
360
- * const highColor = color.from_gradient(150, 0, 100, red, green); // Returns 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
- * ```typescript
414
+ * ```js
415
415
  * const redColor = color.rgb(255, 0, 0);
416
416
  * const transparentRed = color.new(redColor, 50); // 50% transparent red
417
417
  * ```
@@ -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
 
@@ -1,46 +1,110 @@
1
1
  /**
2
- * PineScript comparison operators (`==`, `!=`, `<`, `<=`, `>`, `>=`) on numbers.
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
- * PineScript rules:
5
- * - the operators use an absolute tolerance of 1e-10: `a == b` when `|a - b| <= 1e-10`, `a < b` when
6
- * `b - a > 1e-10` (the same for every magnitude; `0.1 + 0.2 == 0.3` is true)
7
- * - every comparison with an `na` operand is false, `!=` included
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 PineScript's comparison operators. */
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
- /** PineScript `a == b`. */
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
- /** PineScript `a != b` (false when an operand is `na`). */
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
- /** PineScript `a < b`. */
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
- /** PineScript `a <= b`. */
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
- /** PineScript `a > b`. */
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
- /** PineScript `a >= b`. */
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
  }
@@ -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 an object as held by a `var` variable (PineScript `var line l = ...` or `l := line.new(...)` on a `var`
277
- * variable): the maximum count never deletes it, and it still counts. Returns the object.
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
- /** The `var` variable no longer refers to the object (it got another object or `na`). */
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 `var` variable of a drawing type: see {@link varDrawing}. */
344
+ /** A variable that holds one drawing from bar to bar, made by `varDrawing()`. */
325
345
  export interface DrawingVariable<T extends object> {
326
- /** The object of the variable; setting it holds the new object and releases the one before */
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;