oakscriptjs 0.24.0 → 0.25.1

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 +1067 -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 +1067 -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 +1519 -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/docs/guide.md ADDED
@@ -0,0 +1,1185 @@
1
+ # OakScriptJS Complete Guide
2
+
3
+ **The ultimate resource for using OakScriptJS - A simplified PineScript-like library**
4
+
5
+ ## Table of Contents
6
+
7
+ 1. [Introduction](#introduction)
8
+ 2. [For End Users: Using OakScriptJS](#for-end-users)
9
+ 3. [Script API: PineScript-style indicators](#script-api)
10
+ 4. [API Reference](#api-reference)
11
+ 5. [Examples](#examples)
12
+ 6. [Troubleshooting](#troubleshooting)
13
+
14
+ ---
15
+
16
+ ## Introduction
17
+
18
+ OakScriptJS is a simplified JavaScript/TypeScript library that provides the computational core of PineScript's API. It focuses on **calculations and data transformations**. For pre-built indicators, see the [`lightweight-charts-indicators`](https://www.npmjs.com/package/lightweight-charts-indicators) package, built on OakScriptJS.
19
+
20
+ ### Which API to use
21
+
22
+ | Need | API | Import |
23
+ |------|-----|--------|
24
+ | Write an indicator or a strategy the PineScript way (declarations, inputs, plots, `strategy.*`) | Script API | `oakscriptjs/script` |
25
+ | Compute an indicator on plain number arrays, no chart | Array API (`taCore`, `math`, `array`...) | `oakscriptjs` |
26
+ | Chain calculations on bar data in your own code | Series API (`Series`, `ta`) | `oakscriptjs` |
27
+
28
+ The package works with `import` and `require`, in Node.js 18+, browsers and web workers.
29
+
30
+ ### Bars
31
+
32
+ All APIs that take bars use this shape:
33
+
34
+ ```typescript
35
+ import type { Bar } from 'oakscriptjs';
36
+
37
+ const bars: Bar[] = [
38
+ { time: 1704067200, open: 100, high: 105, low: 99, close: 103, volume: 1200 },
39
+ { time: 1704153600, open: 103, high: 107, low: 102, close: 106, volume: 1500 },
40
+ ];
41
+ ```
42
+
43
+ `time` is a UNIX time in seconds (the lightweight-charts unit). The script API also accepts milliseconds with
44
+ `executeScript(body, bars, inputs, { timeUnit: 'ms' })`. Bars are in time order, oldest first.
45
+
46
+ ### Core Capabilities
47
+
48
+ **Level 1: Core Functions (Array-based)**
49
+ Pure calculation functions matching PineScript signatures.
50
+
51
+ ```typescript
52
+ import {taCore} from 'oakscriptjs';
53
+
54
+ const prices = [10, 12, 11, 13, 15];
55
+ const sma = taCore.sma(prices, 3);
56
+ ```
57
+
58
+ **Level 2: Series Class**
59
+ Lazy evaluation with operator chaining.
60
+
61
+ ```typescript
62
+ import { Series } from 'oakscriptjs';
63
+
64
+ const data = [/* bar data */];
65
+ const close = new Series(data, (bar) => bar.close);
66
+ const open = new Series(data, (bar) => bar.open);
67
+
68
+ // Series method calls for arithmetic
69
+ const change = close.sub(open);
70
+ ```
71
+
72
+ **Level 3: TA-Series Functions**
73
+ Series-based wrappers for technical analysis.
74
+
75
+ ```typescript
76
+ import {ta, Series} from 'oakscriptjs';
77
+
78
+ const close = new Series(data, (bar) => bar.close);
79
+ const rsi = ta.rsi(close, 14); // Returns a Series
80
+ ```
81
+
82
+ ---
83
+
84
+ ## For End Users
85
+
86
+ ### Installation
87
+
88
+ ```bash
89
+ # npm
90
+ npm install oakscriptjs
91
+
92
+ # pnpm
93
+ pnpm add oakscriptjs
94
+ ```
95
+
96
+ ### Quick Start: Basic Calculations
97
+
98
+ ```typescript
99
+ import {taCore, math} from 'oakscriptjs';
100
+
101
+ // Price data
102
+ const closes = [100, 102, 101, 103, 105, 104, 106];
103
+
104
+ // Calculate indicators
105
+ const sma = taCore.sma(closes, 5);
106
+ const ema = taCore.ema(closes, 5);
107
+ const rsi = taCore.rsi(closes, 14);
108
+
109
+ // Math operations
110
+ const avg = math.avg(...closes);
111
+ const max = math.max(...closes);
112
+ ```
113
+
114
+ ### Series Class
115
+
116
+ The Series class enables lazy evaluation and operator chaining:
117
+
118
+ ```typescript
119
+ import {Series, ta} from 'oakscriptjs';
120
+
121
+ const bars = [
122
+ { time: 1704067200, open: 100, high: 105, low: 99, close: 103 },
123
+ { time: 1704153600, open: 103, high: 107, low: 102, close: 106 },
124
+ // ... more bars
125
+ ];
126
+
127
+ // Create Series
128
+ const close = new Series(bars, (bar) => bar.close);
129
+ const high = new Series(bars, (bar) => bar.high);
130
+ const low = new Series(bars, (bar) => bar.low);
131
+
132
+ // Calculate with Series
133
+ const range = high.sub(low);
134
+ const rsi = ta.rsi(close, 14);
135
+
136
+ // Extract values
137
+ const rsiValues = rsi.toArray();
138
+ const lastRSI = rsi.last();
139
+ ```
140
+
141
+ ### BarData for Automatic Cache Invalidation
142
+
143
+ The `BarData` class wraps bar arrays and tracks version changes for automatic cache invalidation:
144
+
145
+ ```typescript
146
+ import {BarData, Series, ta} from 'oakscriptjs';
147
+
148
+ // Create BarData wrapper
149
+ const barData = new BarData(bars);
150
+ const close = Series.fromBars(barData, 'close');
151
+ const range = close.sub(Series.fromBars(barData, 'open'));
152
+ const values1 = range.toArray(); // computed and cached
153
+
154
+ // Add new bar - version increments automatically
155
+ barData.push({ time: 1704240000, open: 106, high: 108, low: 105, close: 107 });
156
+
157
+ // Lazy Series (fromBars, arithmetic, offset) detect the version change and recompute
158
+ const values2 = range.toArray(); // one more value
159
+
160
+ // ta.* results are computed when ta.* is called: call it again after the bars change
161
+ const sma = ta.sma(close, 20).toArray();
162
+ ```
163
+
164
+ - Lazy Series recompute when the bars change; there is no manual cache management.
165
+ - A `ta.*` result keeps the values of the bars it was computed on.
166
+ - `Series` still accepts `Bar[]` directly.
167
+
168
+ ### Breaking Closure Chains with materialize()
169
+
170
+ Complex Series expressions create closure chains that keep intermediate Series in memory. Use `materialize()` to break these chains:
171
+
172
+ ```typescript
173
+ import {Series} from 'oakscriptjs';
174
+
175
+ const close = Series.fromBars(bars, 'close');
176
+ const open = Series.fromBars(bars, 'open');
177
+ const high = Series.fromBars(bars, 'high');
178
+ const low = Series.fromBars(bars, 'low');
179
+ const volume = Series.fromBars(bars, 'volume');
180
+
181
+ // Without materialize: keeps all intermediate Series in memory
182
+ const complex = close.sub(open).mul(high).div(low).add(volume);
183
+
184
+ // With materialize: breaks chain after first operations
185
+ const materialized = close.sub(open).mul(high).materialize();
186
+ const result = materialized.div(low).add(volume);
187
+ // Now close, open, high can be garbage collected
188
+ ```
189
+
190
+ **When to use materialize():**
191
+ - Complex expressions with many chained operations
192
+ - Long-running applications where memory is a concern
193
+ - After expensive computations to free intermediate results
194
+ - When you need a "snapshot" of computed values
195
+
196
+ ### Available Namespaces
197
+
198
+ #### Technical Analysis (`ta` and `taCore`)
199
+
200
+ ```typescript
201
+ import {ta, taCore} from 'oakscriptjs';
202
+
203
+ // Core (array-based)
204
+ taCore.sma(priceArray, length)
205
+ taCore.ema(priceArray, length)
206
+ taCore.rsi(priceArray, length)
207
+
208
+ // Series (Series-based)
209
+ ta.sma(closeSeries, length)
210
+ ta.ema(closeSeries, length)
211
+ ta.rsi(closeSeries, length)
212
+
213
+ // Moving averages
214
+ ta.sma(), ta.ema(), ta.wma(), ta.vwma()
215
+
216
+ // Oscillators
217
+ ta.rsi(), ta.macd(), ta.cci(), ta.stoch()
218
+
219
+ // Volatility
220
+ ta.bb(), ta.atr(), ta.stdev()
221
+
222
+ // Crossovers
223
+ ta.crossover(), ta.crossunder(), ta.cross()
224
+ ```
225
+
226
+ #### Mathematics (`math`)
227
+
228
+ ```typescript
229
+ import {math} from 'oakscriptjs';
230
+
231
+ math.abs(x)
232
+ math.max(...values)
233
+ math.min(...values)
234
+ math.avg(...values)
235
+ math.sum(source, length) // sliding sum over `length` bars (PineScript math.sum)
236
+ math.sqrt(x)
237
+ math.pow(x, y)
238
+ math.sin(x), math.cos(x), math.tan(x)
239
+ math.constant(1 / 255) // value of a constant expression in PineScript (not a PineScript function)
240
+ ```
241
+
242
+ Known difference: `math.log10`, `math.exp`, `math.log`, `math.pow`, `math.sin`, `math.cos` and `math.tan` use
243
+ JavaScript's `Math`. PineScript uses other algorithms: the results differ by 1 or 2 units in the last place on part
244
+ of the inputs (`log10` about 4 %, `exp` about 9 %, `sin` / `cos` / `tan` about 3 %, `log` 0.4 %, `pow` 0.05 %).
245
+ This matters only when a script amplifies these tiny differences, for example a comparison `ma > ma[1]` on values
246
+ that grow to 1e195.
247
+
248
+ Constant expressions: PineScript computes an expression of literals and constants (`1 / 255`, `0.1 * 3`,
249
+ `math.sqrt(0.1)`) before the script runs, and rounds the result to 16 decimals when it is 0.001 or more
250
+ (`1 / 255` is 0.003921568627451, not 0.00392156862745098). JavaScript cannot tell a constant from a series value:
251
+ wrap the constant expressions with `math.constant()`. Math functions of constants use JavaScript's `Math` there, so
252
+ `math.constant(math.sqrt(0.1))` is the PineScript value; for `math.log10(c)` use
253
+ `math.constant(math.log(c) / math.log(10))`. Do not wrap an expression with a series operand (`close / 255`).
254
+ This matters when a script truncates such a value: an RGB round trip with `1 / 255` gave the channel 202 in
255
+ PineScript and 201 with the JavaScript value.
256
+
257
+ #### Arrays (`array`)
258
+
259
+ ```typescript
260
+ import {array} from 'oakscriptjs';
261
+
262
+ const arr = array.new_float(10, 0);
263
+ array.push(arr, 5);
264
+ array.get(arr, 0);
265
+ array.size(arr);
266
+ array.sum(arr);
267
+ array.avg(arr);
268
+ array.sort(arr);
269
+ ```
270
+
271
+ ---
272
+
273
+ ## Script API
274
+
275
+ The `oakscriptjs/script` entry lets an indicator be written as a flat
276
+ PineScript-style script: one statement per fact, no calculate() function and
277
+ no separate config objects.
278
+
279
+ ```typescript
280
+ import { executeScript, indicator, input, plot, hline, ta, color, volume } from 'oakscriptjs/script';
281
+
282
+ function ksiScript() {
283
+ indicator('Kinetic Slippage Index (KSI)', { shorttitle: 'KSI', overlay: false, precision: 6 });
284
+
285
+ const volEmaLength = input.int(20, 'Volume EMA Period', { minval: 1 });
286
+ const sigLength = input.int(9, 'Signal Line Period', { minval: 1 });
287
+ const sigSpike = input.float(0, 'Spike Signal Level', { minval: 0 });
288
+
289
+ const trueRange = ta.tr(true);
290
+ const emaVolume = ta.ema(volume, volEmaLength);
291
+ const ksi = emaVolume.gt(0).iff(trueRange.pow(2).div(volume.mul(emaVolume)), 0).mul(1_000_000);
292
+ const signal = ta.ema(ksi, sigLength);
293
+
294
+ const histColor = color.when(ksi.gt(signal), color.new(color.green, 30), color.new(color.red, 30));
295
+
296
+ plot(ksi, 'KSI Histogram', { color: histColor, style: 'histogram', linewidth: 2 });
297
+ plot(signal, 'Signal Line', { color: color.orange, linewidth: 1 });
298
+ hline(0, 'Zero Line', { color: color.gray, linestyle: 'dashed' });
299
+ hline(sigSpike, 'Spike Line', { color: color.orange, linestyle: 'dashed' });
300
+ }
301
+
302
+ const run = executeScript(ksiScript, bars);
303
+ ```
304
+
305
+ Key points:
306
+
307
+ - The script body is a function: `executeScript()` runs it on the bars. The script API calls (`indicator`,
308
+ `input.*`, `plot`, `ta.*` on the builtins, `eachBar`...) work only while the body runs.
309
+
310
+ - `indicator(title, opts)` declares metadata once.
311
+ - `input.*(defval, title, opts)` declares the input AND returns its current
312
+ value (the host-supplied override on recalculations, else the default).
313
+ `input.source()` returns a Series.
314
+ `opts.active` is PineScript's `active`: false greys the input out in the settings (it keeps its value). Pass
315
+ the boolean as in PineScript (`{ active: showMa }`) or a condition on input ids (`{ active: 'show_ma' }`,
316
+ `{ active: { input: 'ma_type', ne: 'None' } }`, `{ not }`, `{ any: [] }`, `{ all: [] }`); a host reads it with
317
+ `isInputActive(config, inputs, configs)`.
318
+ - OHLCV builtins (`open`, `high`, `low`, `close`, `volume`, `hl2`, `hlc3`,
319
+ `ohlc4`, `hlcc4`) are context-bound Series.
320
+ - `ta.*` is the Series API with the chart-implicit functions bound to the
321
+ context bars: `ta.tr(true)`, `ta.atr(14)`, `ta.sar()`, `ta.supertrend()`, ...
322
+ - `plot(series, title, opts)` declares the plot and supplies its data in one
323
+ call; `opts.color` accepts a static color or a per-bar array from
324
+ `color.when(cond, a, b)` (PineScript conditional colors).
325
+ - `fill(a, b, opts)` takes the handles returned by plot()/hline().
326
+ - `alertcondition(cond, title, message)` is collected for the host's alert
327
+ engine.
328
+ - JavaScript has no operator overloading, so Series math is method-chained:
329
+ `ksi.gt(signal).iff(a, b)` instead of `ksi > signal ? a : b`. A JavaScript operator on a Series
330
+ (`close - open`, `rsi > 50`, `` `${rsi}` ``) throws a TypeError that names the method to use.
331
+ - A member that does not exist in `ta`, `math`, `str`, `color`, `input` or `request` throws with the closest
332
+ names: `ta.smaa` gives "ta.smaa does not exist. Did you mean ta.sma?".
333
+
334
+ #### Type-checking a script
335
+
336
+ `oakscriptjs/script/globals` declares the script globals with their types, so the TypeScript checker reports the
337
+ mistakes of a script (plain JavaScript) before it runs, with their line: operators on a Series, a misspelt
338
+ function or option, a wrong number of arguments, a bad shape or style string, TypeScript syntax. A `tsconfig.json`
339
+ next to the scripts, then `npx tsc -p .`:
340
+
341
+ ```json
342
+ {
343
+ "compilerOptions": {
344
+ "allowJs": true, "checkJs": true, "noEmit": true, "strict": true, "noImplicitAny": false,
345
+ "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "moduleDetection": "force",
346
+ "lib": ["ES2022"], "types": ["oakscriptjs/script/globals"]
347
+ },
348
+ "include": ["*.js"]
349
+ }
350
+ ```
351
+
352
+ `lib` leaves out `DOM` (its `open`, `close` and `alert` are other globals); `moduleDetection: "force"` gives each
353
+ script its own top-level names.
354
+
355
+ #### PineScript constants and named arguments
356
+
357
+ The PineScript constant namespaces are exported with their Pine names: `shape.*`, `location.*`, `size.*`,
358
+ `xloc.*`, `yloc.*`, `extend.*`, `display.*`, `format.*`, `font.*`, `scale.*`, `order.*`, `currency.*`,
359
+ `adjustment.*`, `label.style_*`, `line.style_*`, `dayofweek.*`; their values are the strings the functions take
360
+ (`shape.triangleup === 'triangleup'`). The drawing constructors (`label.new`, `line.new`, `box.new`, `table.new`,
361
+ `table.cell`, `polyline.new`, `linefill.new`) take PineScript's named arguments as an object after the positional ones
362
+ (`label.new(c.i, c.high, 'A', { style: label.style_label_down })`), or every argument by name; an unknown name throws
363
+ with the closest names. Inside `eachBar()`, a Series argument of a drawing function is its value on the current bar,
364
+ so `label.new(bar_index, high, 'A')` works as in Pine (`bar_index` and `last_bar_index` are Series).
365
+
366
+ #### Checking a script (`oakscript check`)
367
+
368
+ `npx oakscript check script.js [--spec spec.json] [--bars bars.csv] [--reference expected.csv] [--json]` runs the
369
+ type check above, the declaration run and a run on bars (1,500 synthetic hourly bars by default, a small order engine
370
+ for strategies), and prints the inputs, the outputs (values, first bar, range, signal counts), the trades, the errors
371
+ with their line, warnings (`empty-plot`, `signal-everywhere`, `unused-input`...), the failed items of a spec (expected
372
+ title, pane, inputs, outputs, signals; an unknown spec key is an error, JSON Schema in
373
+ `skills/oakscript/spec.schema.json`), behaviour checks (`--checks checks.js`: `t.plot`, `t.signal`, `t.expect`,
374
+ `t.everyBar`), runs on edge-case bars (`--scenarios`: short history, daily, 1-minute, flat prices, no volume, a gap)
375
+ and the bars that differ from a reference (`--reference`, or `--export` for a chart export with the bars and the
376
+ expected values). Exit code 0 clean, 2 warnings only, 1 errors or failed checks. `checkScript(source, options)` of
377
+ `oakscriptjs/check` gives the same report from code (without the file lines, the time limit and the type check), and
378
+ `assertCheck(report)` throws it in a test. Formats: `skills/oakscript/reference/check.md`. A condition used as a JavaScript boolean (`if (ta.crossover(a, b))`) is not an
379
+ error for the checker nor at run time: an object is always true.
380
+
381
+ Host side: call `executeScript(body, bars, inputs)` to run the script and
382
+ collect `{ metadata, inputConfig, plotConfig, hlineConfig, fillConfig,
383
+ shapeConfig, barColorConfig, defaultInputs, result }`. Re-run it whenever bars
384
+ or inputs change — that is PineScript's recalculation model. Executions must be
385
+ serialized (one script at a time); a Web Worker does this naturally.
386
+
387
+ ### defineIndicator and strict mode
388
+
389
+ New to coding? Start with [Your first indicator in 5 minutes](first-indicator.md) and the [recipes](recipes.md).
390
+
391
+ `defineIndicator(body, options?)` makes a script body into a ready-to-use indicator: its declarations
392
+ (`metadata`, `inputConfig`, `defaultInputs`, `plotConfig`, `hlineConfig`, `fillConfig`, `shapeConfig`,
393
+ `alertConditions`, `outputs`...) are read from a first run on two sample bars, the first time one is asked for;
394
+ `calculate(bars, inputs?, chart?)` returns the result of a run, `run()` everything a run produced (with its
395
+ `warnings`), `createRun(inputs?, chart?)` a live run (see [Incremental runs](#incremental-runs-createscriptrun)). `id`
396
+ is a name made from the title ("My RSI" gives "my-rsi"). Not a PineScript function.
397
+
398
+ Strict mode is on in `defineIndicator` (`{ strict: false }` turns it off) and off in `executeScript` /
399
+ `createScriptRun` unless `{ strict: true }` is given. In strict mode, these mistakes throw a `ScriptError` whose
400
+ message says what to change; without it, they pass silently as in PineScript:
401
+
402
+ - an input value given by the host that the script does not declare (`{ lenght: 5 }`), of the wrong type, out of
403
+ `minval` / `maxval`, not a whole number for `input.int`, not one of the `options`, not a colour or a source;
404
+ - an unknown option of `plot`, `hline`, `plotshape`, `plotchar`, `bgcolor`, `barcolor` (`colour`, `text_color`);
405
+ - a text that is not a colour (`"reddd"`, or a colour name such as `"red"`: write `color.red`).
406
+
407
+ Every run lists in `warnings` what a script usually does not mean (drawings deleted because there were more than
408
+ the maximum count); `defineIndicator` passes them to `console.warn` (option `onWarning`). `plot()` of a number draws
409
+ a flat line, in every mode.
410
+
411
+ ```typescript
412
+ import { defineIndicator, indicator, input, plot, ta, close } from 'oakscriptjs/script';
413
+
414
+ const ewo = defineIndicator(() => {
415
+ indicator('Elliott Wave Oscillator');
416
+ const fast = input.int(5, 'Fast length', { minval: 1 });
417
+ const slow = input.int(35, 'Slow length', { minval: 1 });
418
+ plot(ta.ema(close, fast).sub(ta.ema(close, slow)), 'EWO', { style: plot.style_histogram });
419
+ plot(0, 'Zero');
420
+ });
421
+ ewo.defaultInputs; // { fast_length: 5, slow_length: 35 }
422
+ ewo.calculate(bars, { fast_length: 8 }).plots.plot0;
423
+ ```
424
+
425
+ ### Plain words, formulas, JSON and preview
426
+
427
+ Not PineScript; for people who are new to coding (see [Indicators without code](no-code.md) for the details):
428
+
429
+ - `calc.*`: plain-English names beside `ta.*`: `calc.average(source, length, kind)` ('simple', 'exponential',
430
+ 'weighted', 'smoothed', 'hull', 'volume-weighted'), `calc.crossesAbove`, `calc.crossesBelow`, `calc.crosses`,
431
+ `calc.above`, `calc.below`, `calc.between`, `calc.previous`, `calc.change`, `calc.percentChange`, `calc.highest`,
432
+ `calc.lowest`, `calc.isRising`, `calc.isFalling`, `calc.standardDeviation`, `calc.ifElse`, `calc.all`, `calc.any`.
433
+ They take Series or numbers and check their lengths.
434
+ - `color.fade(color, amount)`: `amount` from 0 (unchanged) to 1 (invisible); `color.fade(c, 0.8)` is `color.new(c, 80)`.
435
+ - `formula(text, variables?)`: a calculation as text, `formula("rsi(close, length) > 70", { length })`, read by a small
436
+ parser (never run as code). `evaluateFormula` gives a number when the formula uses no Series; `FORMULA_FUNCTIONS`
437
+ lists its functions. A mistake throws a `ScriptError` with a caret under it.
438
+ - `indicator(title, { pane: 'price' | 'separate' | 'auto' })` instead of `overlay`; 'auto' chooses at the end of the run:
439
+ the price chart when nine values in ten of the shown plots are within the price range of the bars (widened by a
440
+ quarter). `defineIndicator` decides on its sample bars (prices near 5000), so an RSI never lands on a chart of a
441
+ stock at 100.
442
+ - `input.*(..., { id })`: the id of the input instead of the one made from the title.
443
+ - `ScriptOptions.palette` (true, or a list of colours): plots without a colour take the next colour of
444
+ `DEFAULT_PALETTE`; `ScriptOptions.plotIds: 'title'`: plot ids made from the titles (`plots.fast_ma`). In
445
+ `defineIndicator`, `palette` is on by default and `plotIds` stays 'index'.
446
+ - `defineIndicatorFromJson(spec)`, `indicatorBodyFromJson(spec)`, `checkIndicatorJson(spec)`: an indicator described in
447
+ JSON (settings, named formulas, plots, levels, fills, signals with alerts, background and bar colours).
448
+ - `oakscript preview <file.js | file.json>`: a chart in the browser with the settings beside it, drawn again on each
449
+ save (`--bars prices.csv`, `--port`).
450
+
451
+ ### Visual outputs (plotshape, plotchar, bgcolor, barcolor)
452
+
453
+ Beyond `plot`, the script API emits per-bar markers and colors. Each is a pure
454
+ function of an already-computed Series.
455
+
456
+ ```typescript
457
+ import { plotshape, plotchar, bgcolor, barcolor, color, close, ta, shape, location } from 'oakscriptjs/script';
458
+
459
+ // Marker on each bar where the condition holds
460
+ plotshape(ta.crossover(fast, slow), 'Cross', {
461
+ style: shape.triangleup, // shape.* (the string 'triangleup' works too)
462
+ location: location.belowbar, // location.abovebar | belowbar | top | bottom | absolute
463
+ color: color.green,
464
+ text: 'B',
465
+ tooltip: 'Bullish cross', // extension over PineScript, for label-style ports
466
+ });
467
+
468
+ // A character marker
469
+ plotchar(close.gt(100), 'Above 100', { char: '↑', location: 'abovebar' });
470
+
471
+ // Per-bar background / candle color: static color or a per-bar array
472
+ bgcolor(color.when(fast.gt(slow), color.new(color.green, 90))); // uncolored where false
473
+ barcolor(color.when(close.gt(close.offset(1)), color.green, color.red));
474
+ ```
475
+
476
+ `color.when(cond, colorTrue, colorFalse?)` builds the per-bar array; omit
477
+ `colorFalse` to leave those bars uncolored (PineScript `na`).
478
+ `color.from_gradient(value, bottom, top, bottomColor, topColor)` with a Series argument (or a per-bar colour array)
479
+ gives the gradient colour of each bar: `plot(r, 'RSI', { color: color.from_gradient(r, 30, 70, color.red, color.green) })`.
480
+
481
+ `na(x)` and `nz(x, replacement)` take a Series as in PineScript: `na(x)` is a Series of 1 / 0 (1 where x is NaN or
482
+ ±Infinity), `nz(x, open)` replaces those values with the replacement of the same bar (a number, default 0, or a
483
+ Series). On numbers (in `eachBar`) they return a boolean and a number.
484
+
485
+ The run result carries the data: `result.markers` (`MarkerData[]`),
486
+ `result.bgColors` (`BgColorData[]`) and `result.barColors` (`BarColorData[]`).
487
+ `plotshape`/`plotchar` are also declared in `shapeConfig`, and `bgcolor`/`barcolor`
488
+ in `barColorConfig`, for the host UI.
489
+
490
+ A marker uses the lightweight-charts vocabulary: `position` (`aboveBar`,
491
+ `belowBar`, `top`, `bottom`, and for `location.absolute` `atPriceTop` /
492
+ `atPriceBottom` / `atPriceMiddle` with `price`), `shape` (`triangleUp`,
493
+ `labelDown`, ...), `color` (default `#2962FF`), `textColor`, `size`. A `plotchar`
494
+ marker has its character in `char` (and the shape `circle`).
495
+
496
+ ### Candles, bars, drawings and tables
497
+
498
+ ```typescript
499
+ import { plotcandle, plotbar, label, line, box, table, position, text, eachBar, extend } from 'oakscriptjs/script';
500
+
501
+ // plotcandle / plotbar: one candle / bar per bar where open, high, low and close are not na
502
+ plotcandle(haOpen, haHigh, haLow, haClose, 'Heikin Ashi', { color: color.when(haClose.gt(haOpen), '#26A69A', '#EF5350') });
503
+ plotbar(open, high, low, close, 'OHLC', { color: '#787B86' });
504
+
505
+ // drawings: the objects alive after the last bar are returned
506
+ eachBar((c) => {
507
+ if (c.i === c.n - 1) {
508
+ label.new(c.i, c.high, 'Last', { color: '#2962FF', style: label.style_label_down, textcolor: '#FFFFFF' });
509
+ line.new(c.i - 20, c.get(low, 20), c.i + 10, c.low, { extend: extend.right });
510
+ }
511
+ });
512
+
513
+ // tables
514
+ const t = table.new(position.top_right, 2, 2, '#131722');
515
+ table.cell(t, 0, 0, 'RSI', 0, 0, '#FFFFFF');
516
+ table.cell(t, 1, 0, '54.2', 0, 0, '#FFFFFF', text.align_right);
517
+ table.merge_cells(t, 0, 1, 1, 1);
518
+ ```
519
+
520
+ The run result has `plotCandles` and `plotBars` (keyed by the ids of
521
+ `candleConfig`), and `labels`, `lines`, `boxes`, `linefills`, `polylines`,
522
+ `tables`: the drawings alive after the last bar (deleted ones and the ones over
523
+ `max_*_count` are gone). In the drawings:
524
+
525
+ - x coordinates are bar times: a `bar_index` x is the time of that bar, or of a
526
+ future bar after the last bar (`barTime(bars, index)`: last bar time + k times
527
+ the most frequent bar gap); a `bar_time` x (UNIX ms) is converted to the unit of
528
+ the bar times
529
+ - an object with an `na` coordinate is not drawn
530
+ - a property the script did not set is omitted (the renderer uses the PineScript
531
+ default); a colour set to `na` is `'transparent'`
532
+
533
+ `drawingOutputs(bars)` (from `oakscriptjs`) gives the same fields for drawings
534
+ made outside a script run.
535
+
536
+ In PineScript, an object that a `var` variable of the drawing type refers to is
537
+ never deleted by `max_*_count`, and it still counts. JavaScript has no `var`
538
+ declaration to observe, so the script says it with `varDrawing()`:
539
+
540
+ ```typescript
541
+ // Pine: var line level = na
542
+ // level := line.new(bar_index, close, bar_index + 1, close)
543
+ const level = varDrawing<Line>();
544
+ eachBar((c) => {
545
+ level.value = line.new(c.i, c.close, c.i + 1, c.close); // holds the new line, releases the one before
546
+ });
547
+ ```
548
+
549
+ On the bar where the variable gets the object (or lets it go), the object is
550
+ deleted only when the objects that can go are not enough (#193); from the next
551
+ bar on, never (a released object, from the next bar on, like any other).
552
+
553
+ Only the variable protects: an object kept in an array or in a field is deleted
554
+ like any other. `holdDrawing(obj)` / `releaseDrawing(obj)` do the same without a
555
+ variable object.
556
+
557
+ On the last bar `max_*_count` has rules of its own: a cut deletes the objects
558
+ of the bars before first, at most those, and the count of `line.delete` /
559
+ `label.delete` / `box.delete` calls of the bars before moves the limit.
560
+ `eachBar` handles it. A port with its own bar loop says which bar is the last
561
+ one:
562
+
563
+ ```typescript
564
+ for (let i = 0; i < bars.length; i++) {
565
+ setDrawingBar(i, i === bars.length - 1);
566
+ // ... drawings of the bar
567
+ }
568
+ setDrawingBar(null);
569
+ ```
570
+
571
+ A live update of such a port calculates the forming bar again from the drawings at
572
+ the end of the last confirmed bar: `saveDrawingCheckpoint()` there, and
573
+ `restoreDrawingCheckpoint(checkpoint)` before the forming bar (on each new price)
574
+ or the new bars are calculated. The drawings are then those of a full run on the
575
+ same bars: what the forming bar created, changed or deleted is undone, the objects
576
+ of the bars before are the same objects in the same order, and the maximum counts,
577
+ `var` holds (`varDrawing()` variables too), linefills and last-bar rules go on as
578
+ in a full run. The checkpoint holds the whole registry of the study, so other
579
+ studies may use the registry between two updates: put it back where a full run
580
+ calls `resetDrawings()`. The port keeps its own variables (the objects it refers
581
+ to, its arrays of objects) with the checkpoint (#203).
582
+
583
+ ### Per-bar stateful execution (eachBar)
584
+
585
+ The Series API is vectorized. For logic PineScript writes with persistent state
586
+ (`var`, `:=`) or imperative loops, `eachBar(fn)` runs a callback once per bar and
587
+ collects the returns into a Series. Inside the callback values are plain numbers,
588
+ so native JS operators, `if`/`for`/`while` and closure `let` variables work.
589
+ `eachBar()` is called inside the script body, like the other script API calls.
590
+
591
+ ```typescript
592
+ import { eachBar, seriesOf, close, high } from 'oakscriptjs/script';
593
+
594
+ let dir = 0; // var dir = 0
595
+ const trend = eachBar((c) => {
596
+ if (c.close > c.get(close, 1)) dir = 1; // dir := 1 ; c.get(src, k) is src[k]
597
+ else if (c.close < c.get(close, 1)) dir = -1;
598
+ return dir; // collected into a Series (bool → 1/0, void → na)
599
+ });
600
+ ```
601
+
602
+ The bar context `c` exposes `c.open/high/low/close/volume`, `c.i` (bar_index),
603
+ `c.n`, `c.time`, `c.get(series, offset)` for history on any Series, and
604
+ `c.prev(offset)` for this block's own previous output. Accumulate a side array in
605
+ the closure and wrap it with `seriesOf(values)` for a second output.
606
+
607
+ - Compute the `ta.*` Series before `eachBar()` and read them with `c.get()`. A `ta.*` function called inside the
608
+ callback throws (it would compute the whole Series on every bar, with no per-bar history); see callsite below for
609
+ the stateful versions. The `ta.*` variables (`ta.obv`, `ta.accdist`...) are Series: read them with `c.get()`.
610
+ - `c.get(src, k)` needs `k >= 0`: a negative offset would read a future bar, so it throws.
611
+ - History limit, as PineScript (runtime error RE10008): a script series keeps at most 5000 bars of history.
612
+ `c.get(x, k)` or `x.offset(k)` with `k > 5000` throws. The history buffer of a script series grows as PineScript
613
+ grows it (242 bars at the start, then x 1.618 when the largest reference of a bar goes past it; a jump sets it to
614
+ the reference); a buffer above 5000 stops the script on the next bar, so `c.get(x, c.i)` stops on bar 4348. The
615
+ built-in `open`, `high`, `low`, `close`, `volume`, `hl2`, `hlc3`, `ohlc4`, `hlcc4` keep the whole history.
616
+ - JS comparison operators do not follow the PineScript rules: PineScript compares with a 1e-10 tolerance, and a
617
+ comparison with `na` is false. Use `compare.eq/ne/lt/le/gt/ge(a, b)` from `oakscriptjs` for the PineScript
618
+ result (e.g. `compare.gt(c.close, c.get(ma))`).
619
+ - `persist(initial)` is a `var` kept by the runtime: declared in the script body, read and written with `.value` in
620
+ one `eachBar()` callback. In a plain run it is a plain variable; in an incremental run (below) the runtime puts it
621
+ back to its value at the last confirmed bar before the forming bar is calculated again.
622
+
623
+ ```typescript
624
+ const dir = persist(0); // var dir = 0
625
+ const trend = eachBar((c) => {
626
+ if (c.close > c.get(close, 1)) dir.value = 1;
627
+ else if (c.close < c.get(close, 1)) dir.value = -1;
628
+ return dir.value;
629
+ });
630
+ ```
631
+
632
+ ### Incremental runs (createScriptRun)
633
+
634
+ On a live chart the forming bar changes on every update. `createScriptRun(body, inputs, chart, options)` (host side,
635
+ like `executeScript`) calculates the newest bars only (#196):
636
+
637
+ ```typescript
638
+ import { createScriptRun } from 'oakscriptjs/script';
639
+
640
+ const run = createScriptRun(body, inputs, chart);
641
+ let result = run.update(bars); // full run on the history
642
+ // later: the same bars with a new price of the forming bar, or new bars after it
643
+ result = run.update(nextBars); // result.incremental, result.from (first bar calculated)
644
+ ```
645
+
646
+ The first update is a full run. It keeps what the script created (its Series, `ta.*` calls, `eachBar()` blocks,
647
+ `persist()` boxes and plots, matched by creation order) with their state at the end of the last confirmed bar. An
648
+ update whose bars equal the previous ones up to its forming bar runs the body again from that bar only: the Series
649
+ keep their earlier values, the `ta.*` calls with a `taStep` machine step the newest bars, the `eachBar()` callbacks run
650
+ from that bar with their `persist()` boxes and history buffers put back. The result equals a full run on the same
651
+ bars, bit for bit. Any other change (history loaded or adjusted, other chart fields) runs the script in full.
652
+
653
+ Drawings are resumed when one `eachBar()` block uses them: its checkpoint holds the registry and the state of each
654
+ object (fields, deletion, `var` holds), put back on the same objects, so a `persist()` box or a `varDrawing()` that
655
+ holds a drawing stays valid. The drawings the script body creates before the blocks (a dashboard `table.new`) are the
656
+ same objects on each run. A strategy is resumed when its order engine implements `save()` / `restore()`
657
+ (`StrategyEngine`): the next run's engine gets the state of the last confirmed bar.
658
+
659
+ Calculated in full (same results, more time): a script whose `eachBar()` callback changes a variable declared outside
660
+ it (read from the callback's source: `x = ...`, `x++`, `x.push(...)`, `array.push(x, ...)`; a `persist` box's
661
+ `.value` is allowed), reads a `persist` box outside a callback or from two callbacks, uses drawings in two blocks or in
662
+ the body after a block, uses `request.security`, a strategy engine without `save()` / `restore()`, `varip`,
663
+ `timenow`, `last_bar_index`, `c.n` or `barstate.islastconfirmedhistory` (these four depend on the bar count or the
664
+ clock). `run.fullRunReason` names the first one met; `oakscript check` prints it (`liveUpdates` of the report). A
665
+ change made by a function the callback calls is not read from the source: the first resumed updates (`verify`,
666
+ default 2) are also calculated in full and compared, and a difference makes the next updates full runs.
667
+
668
+ The `ta.*` calls with a `taStep` machine step only the newest bars; the others (`pivothigh`, `highestbars`, `sar`,
669
+ `vwap`...) are correct in a resumed update but calculated on the whole history.
670
+
671
+ On 10,000 daily bars, a script with 13 plots (`sma`, `ema`, `rsi`, `macd`, `bb`, `atr`, `stoch`, an `eachBar` with
672
+ `persist`): a full run 7.4 ms, a resumed update 0.4 ms.
673
+
674
+ `math.random` is not resumed either (its generators start again on each run).
675
+
676
+ ### Intrabar runs of a strategy (executeIntrabar)
677
+
678
+ A strategy calculated on the ticks of history bars or after order fills runs again inside a bar:
679
+ `executeIntrabar(body, bars, inputs, chart, { bar, lastBarIndex, engine, recorder })`, called by the host's order engine
680
+ from `processBar` of the main run (`bars`: the main run's bars up to `bar`, the last one as it stands at the tick). The
681
+ script's variables come back to their state at the start of the bar, `varip` ones are kept.
682
+
683
+ The intrabar runs of a backtest (same `recorder`, script, inputs, chart and engine) are resumed as in
684
+ `createScriptRun` (#206): each one calculates its bar, and the bars since the previous intrabar run, from the state the
685
+ previous one kept, instead of all the bars before it. The order calls and `strategy.*` reads are those of the full
686
+ replay; a resumed run gives its order calls to the engine once it has ended. The same scripts are calculated in full
687
+ (state outside `persist()` boxes, `request.security`, `timenow`, `math.random`...), and also a `varip` read outside
688
+ `strategy.eachBar()`; `c.n`, `last_bar_index` and `barstate.islastconfirmedhistory` are resumed (the chart's last bar
689
+ does not change during a backtest). The first resumed runs are also calculated in full and compared (`verify`, default
690
+ 2; the order calls, the reads and the `varip` values): a difference makes the next runs full ones. The result
691
+ (`IntrabarUpdate`: `from`, `incremental`, `fullRunReason`) and `recorder.intrabarFullRunReason` give the reason;
692
+ `resume: false` calculates every run in full.
693
+
694
+ On 2,400 daily bars with 4 ticks per bar, a strategy with `highest`, `lowest`, `atr`, `ema`, `sma` and a `persist`
695
+ stop: 4.7 s with full replays, 0.15 s resumed (11,500 bars: 1.6 s).
696
+
697
+ ### Higher timeframes (request.security)
698
+
699
+ `request.security(symbol, timeframe, expression, gaps?, lookahead?)` runs `expression` on higher-timeframe bars
700
+ built from the chart bars (chart symbol only: `''`, `syminfo.tickerid`, `ticker.heikinashi(...)`).
701
+
702
+ ```typescript
703
+ import { request, ta, close } from 'oakscriptjs/script';
704
+
705
+ const dailyEma = request.security('', 'D', () => ta.ema(close, 20));
706
+ ```
707
+
708
+ - With the default `barmerge.lookahead_off`, a period's value appears on the chart bar that completes it.
709
+ - Compute the series **inside** the expression. A series computed outside runs on the chart bars, not on the
710
+ higher-timeframe bars, so `request.security('', 'D', () => myEma)` throws.
711
+
712
+ #### Other symbols
713
+
714
+ The library does not fetch data. For another symbol the host gives the bars through the chart context; the
715
+ expression runs on them and the values are merged on the chart bars as PineScript does.
716
+
717
+ ```typescript
718
+ import { executeScript, request, close, MissingSymbolDataError } from 'oakscriptjs/script';
719
+
720
+ const chart = {
721
+ tickerid: 'NASDAQ:AAPL', timeframe: '1D', timezone: 'America/New_York', session: '0930-1600',
722
+ bars: (symbol, timeframe) => cache.get(`${symbol}|${timeframe}`), // undefined: not loaded yet; []: no such symbol
723
+ symbolInfo: (symbol) => ({ timezone: 'Etc/UTC', session: '24x7' }), // calendar of the other symbol
724
+ };
725
+ try {
726
+ executeScript(() => { plot(request.security('BITSTAMP:BTCUSD', 'D', () => close)); }, bars, {}, chart);
727
+ } catch (e) {
728
+ if (e instanceof MissingSymbolDataError) { /* load e.requests ({ symbol, timeframe }), then run again */ }
729
+ }
730
+ ```
731
+
732
+ - Lookahead off shows the last bar of the other symbol whose close time is at or before the close of the chart bar
733
+ (a stock chart shows the crypto bar of the day before, a crypto chart the stock bar of the same day). Lookahead on:
734
+ by open time on intraday charts, by trading day (D), week start (W) or month start (M) on D / W / M charts.
735
+ - Close times and trading days need the calendar of both symbols (`timezone` + `session`, and `symbolInfo` for the
736
+ other). Without them a fallback is used that is exact for symbols on the same calendar and for 24x7 symbols only.
737
+ - `timeframe` is passed normalised ("1D", "1W", "60"); a lower timeframe than the chart's throws.
738
+ - A port without the script API can use `securityOther(chartBars, otherBars, timeframe, chart, { lookahead, gaps,
739
+ other })`: the index of the other bar shown on each chart bar (-1 for na).
740
+
741
+ #### Lower timeframes
742
+
743
+ `request.security` on a timeframe lower than the chart's (the chart symbol or another one) and
744
+ `request.security_lower_tf` read the lower-timeframe bars from `ChartContext.bars` as well (for the chart symbol:
745
+ `bars(tickerid, timeframe)`). Lookahead off shows the last lower bar that closes by the close of the chart bar,
746
+ lookahead on the last one that opened by its open. `request.security_lower_tf(symbol, timeframe, expression)` returns
747
+ one array per chart bar: the values on the lower bars that close inside the chart bar (after its open, at or before
748
+ its close). Ports use `securityLowerTf(chartBars, lowerBars, timeframe, chart, { other })`, which gives the
749
+ `[from, to)` range of lower bars of each chart bar. As PineScript, only the last 100,000 lower bars are given out
750
+ (`MAX_INTRABARS`; `{ maxIntrabars }` changes it): older chart bars get an empty array.
751
+
752
+ #### Seed data
753
+
754
+ `request.seed(source, symbol, expression, ignore_invalid_symbol?)` (#205) is `request.security(<ticker>, "",
755
+ expression)` on a seed data series: the ticker is `ChartContext.seedSymbol(source, symbol)`, by default
756
+ `"<SOURCE>:<SYMBOL>"` upper-cased (`request.seed("seed_crypto_santiment", "BTC_DEV_ACTIVITY", () => close)` reads
757
+ `SEED_CRYPTO_SANTIMENT:BTC_DEV_ACTIVITY`), and its bars come from `ChartContext.bars` on the chart timeframe.
758
+ `calc_bars_count` throws, as in `request.security`.
759
+
760
+ #### Dividends, splits and earnings
761
+
762
+ `request.dividends(ticker, field?, gaps?, lookahead?)` (`dividends.net`, default, or `dividends.gross`),
763
+ `request.splits(ticker, field, gaps?, lookahead?)` (`splits.numerator` or `splits.denominator`) and
764
+ `request.earnings(ticker, field?, gaps?, lookahead?)` (`earnings.actual`, default, `earnings.estimate` or
765
+ `earnings.standardized`) read the events the host gives with `ChartContext.events(symbol)` (#211): `{ dividends,
766
+ splits, earnings }`, each a list of `{ time, ... }` (ms). `undefined` means not loaded yet (the run ends with a
767
+ `MissingSymbolDataError` whose request has `events: true`), `{}` a symbol without events.
768
+
769
+ They are placed as measured on PineScript: an event belongs to the period of the chart timeframe that contains its
770
+ time, in UTC (its UTC day on a daily chart, its UTC week from Monday on a weekly one). Lookahead off shows it from the
771
+ first chart bar that closes at or after the end of that period: a dividend whose ex-date is a Monday shows on
772
+ Tuesday's daily bar and on Monday's first hourly bar; earnings published after Thursday's close on Friday's bars.
773
+ Lookahead on shows it from the first chart bar that closes after the period's start (Monday's daily bar). Gaps off keeps
774
+ the last value; gaps on shows it on that bar only. Dividends are given as declared (not adjusted for later splits),
775
+ earnings per share adjusted for later splits, as PineScript gives them. A field no event has (an estimate the host
776
+ does not have) throws. Deliberate difference: PineScript gave na with gaps on for the dividends of every symbol
777
+ measured after 2013, and split-adjusted dividends with lookahead on; here both follow the rules above.
778
+
779
+ `dividends.future_amount`, `dividends.future_ex_date`, `dividends.future_pay_date`, `earnings.future_eps`,
780
+ `earnings.future_revenue`, `earnings.future_time` and `earnings.future_period_end_time` read the first event after the
781
+ current time of the run, when the host says that its lists hold the announced ones (`future: { dividends: true,
782
+ earnings: true }`); otherwise they throw.
783
+
784
+ ### Symbol information (syminfo)
785
+
786
+ Every `syminfo.*` field of PineScript v6 reads the chart context (inside `request.security`, the requested symbol's
787
+ `SymbolInfo`). A field the host gives as `null` is na, as PineScript gives it for a symbol without one (`""` for a
788
+ text, which `na()` takes as na: `syminfo.basecurrency` of a stock); a field the host does not give throws.
789
+ `syminfo.ticker`, `syminfo.prefix` and `syminfo.main_tickerid` default to the parts of the ticker id (the chart's
790
+ own symbol for `main_tickerid`, also inside `request.security`), `syminfo.root` to the ticker without the `1!` of a
791
+ continuous future or the month code and year of a contract (`ESZ2026` with `symbolType: 'futures'` gives `ES`).
792
+ `syminfo.recommendations_*` and `syminfo.target_price_*` come from `recommendations` and `targetPrice`.
793
+
794
+ ### The session of a chart context without a script
795
+
796
+ Code that has its own bar loop can read the same session values from a chart context (timeframe, time zone,
797
+ session with its corrections and holidays). Bar times are in the unit of the context (seconds by default);
798
+ PineScript time values come back in ms.
799
+
800
+ ```typescript
801
+ import { periodTime, tradingDayTime, chartSessionFlags, resampleSession, mapToChart, barTimeAfter, barsUntil } from 'oakscriptjs';
802
+
803
+ const chart = { timeframe: '60', timezone: 'America/New_York', session: { session: '0930-1600', holidays: '20260907' } };
804
+
805
+ periodTime(bar.time, 'D', chart); // time("D")
806
+ periodTime(bar.time, '240', chart, '0930-1200,1300-1600', 'Europe/Paris'); // time("240", session, timezone)
807
+ tradingDayTime(bar.time, chart); // time_tradingday
808
+ chartSessionFlags(times, chart); // session.isfirstbar, islastbar, ismarket ...
809
+
810
+ // request.security on a higher timeframe, following the session and the holidays
811
+ const daily = resampleSession(bars, 'D', chart);
812
+ const dailyClose = mapToChart(daily.bars.map((b) => b.close), daily.group, daily.latest, false, false);
813
+
814
+ // a drawing that ends 10 bars after the last bar, or at a later time: weekends and holidays are skipped
815
+ barTimeAfter(lastBar.time, 10, chart); // open time of that future bar
816
+ barsUntil(lastBar.time, lastBar.time + 3 * 86400, chart); // bars to the bar of that time
817
+ ```
818
+
819
+ `time(timeframe, session, timezone)` in a script tests the session as PineScript does: an intraday timeframe is na
820
+ outside the session (the rules of `time.inSession`, its periods aligned on the start of the run), `"D"` is na outside
821
+ the day's session period, and a timeframe of more than one day (`"2D"`, `"W"`, `"M"`) is never na: it keeps the
822
+ period's time between the runs. On a day when the clocks change, `"D"` places the wall times of the session string
823
+ as the JVM does (a skipped time moves past the gap, a repeated time is its first pass, the end is the minute before
824
+ it plus one), which is not always the placement of `time.inSession`. A bar that opens after an early close has no
825
+ `"D"` and no intraday period (`time("D")`, `time("240")` are na on it), but `request.security` puts it in the D bar
826
+ of the day and in an intraday bar of its own.
827
+
828
+ ### ta.* calls in conditional code (callsite)
829
+
830
+ In PineScript every `ta.*` call keeps its own history, fed only on the bars where the call runs. This matters in
831
+ an `if` block and, since v6, in the right operand of `and` / `or`, which run only when the left operand does not
832
+ decide the result (`a or b`: bars where `a` is false; `a and b`: bars where `a` is true). A vectorized Series call
833
+ sees every bar, so such calls need a call site from the `callsite` namespace:
834
+ `callsite.whenCalled(called, fn, ...sources)` when the bars are known in advance, or the stateful
835
+ `callsite.crossover()`, `crossunder()`, `cross()`, `barssince()`, `lowestByBar()`, `highestByBar()`,
836
+ `lowestbars()`, `highestbars()`, `pivothigh()`, `pivotlow()`, `lowest()`, `highest()`, `linreg()`, `sum()`, `sma()`,
837
+ `stdev()` in a bar loop.
838
+ `callsite.crossoverByBar()` / `crossunderByBar()` (`site(bar_index, close, level)`) are `ta.crossover` /
839
+ `ta.crossunder` called several times on one bar (a `for` loop over zones): every call compares with the last call of
840
+ the previous bar, as PineScript; `callsite.crossover()` compares with the previous call, also on the same bar.
841
+ `callsite.linreg()` takes the bar index: PineScript's `ta.linreg` keeps its window by bar, so in an `if` block the
842
+ bars before the first call count as 0 (`site(bar_index, close, 10, 0)` on the bars where the block runs).
843
+ `callsite.lowestByBar()` / `highestByBar()` / `lowestbars()` / `highestbars()` (`site(bar_index, low, 6)`) and
844
+ `pivothigh()` / `pivotlow()` (`site(bar_index, high, 5, 5)`) keep the non-na values of their calls: the result is the
845
+ extreme of the last `length` calls (of the calls so far when there are fewer), `na` before bar `length - 1`. The
846
+ bar index gives that warm-up, the offsets of `highestbars` and the bar of a pivot; in a loop, the calls of one bar
847
+ share one kept value. The length can change from one call to the next.
848
+ `callsite.lowest()` / `highest()` are the same sites called with `(value, length)` on every bar, for `ta.lowest` /
849
+ `ta.highest` with a series length (a different length on each bar):
850
+
851
+ ```typescript
852
+ // Pine: lowPrice = ta.lowest(close[1], lookback) // lookback changes per bar
853
+ const lowPrice = callsite.lowest();
854
+ const lows = closes.map((_, i) => lowPrice(i > 0 ? closes[i - 1]! : NaN, lookback[i]!));
855
+ ```
856
+
857
+ `ta.sma`, `ta.stdev`, `ta.variance` and `math.sum` take a series length directly, with no call site: pass one length
858
+ per bar (an array or a Series), as PineScript's series int length. Each bar sums its last `length` values (the
859
+ correctly rounded window sum, bit for bit as PineScript):
860
+
861
+ ```typescript
862
+ // Pine: avg = ta.sma(close, lookback) // lookback changes per bar
863
+ const avg = taCore.sma(closes, lookback);
864
+ ```
865
+
866
+ A `ta.*` call inside a `for` / `while` loop is one call site too: it keeps one history value per bar, the value of
867
+ its last call on that bar, and every call on the bar starts from the earlier bars. `callsite.sum()` / `sma()` /
868
+ `stdev()` (`math.sum` / `ta.sma` / `ta.stdev`) take the bar index to tell the bars apart. The length can change from
869
+ one call to the next (for example a loop over several lengths): each call moves the kept sum to its own length, as a
870
+ series length does:
871
+
872
+ ```typescript
873
+ // Pine: for i = 0 to 2
874
+ // avg = ta.sma(close * (1 + 0.01 * i), 10)
875
+ const avgSite = callsite.sma();
876
+ for (let b = 0; b < closes.length; b++) {
877
+ for (let i = 0; i <= 2; i++) {
878
+ const avg = avgSite(b, closes[b]! * (1 + 0.01 * i), 10);
879
+ }
880
+ }
881
+ ```
882
+
883
+ ```typescript
884
+ import { callsite } from 'oakscriptjs';
885
+
886
+ // Pine: longCond = longUp or (src > sigLine and ta.barssince(longUp) <= lookback)
887
+ const since = callsite.barssince();
888
+ const longCond = eachBar((c) => {
889
+ const up = c.get(longUp) === 1;
890
+ // the right operand runs only when longUp is false, so barssince() never sees true here
891
+ return up || (c.get(src) > c.get(sigLine) && since(up) <= lookback);
892
+ });
893
+ ```
894
+
895
+ ### ta.* one bar at a time (taStep)
896
+
897
+ `taStep` gives one state machine per `ta.*` call, for code that calculates bar by bar and receives live updates of
898
+ the forming bar (#196). `step(...)` gives the result of the current bar from the kept state of the earlier bars and can
899
+ be called again on the same bar (each tick of the forming bar starts again from the same state); `commit()` ends the
900
+ bar and keeps its last step. A bar without a step is not in the history of the call, as a `ta.*` call in an `if`
901
+ block. Driven once per bar over an array, each machine gives the doubles of the `taCore` function, bit for bit.
902
+
903
+ ```typescript
904
+ import { taStep } from 'oakscriptjs';
905
+
906
+ const rsi = taStep.rsi(14);
907
+ const bands = taStep.bb(20, 2);
908
+ // history: one step and one commit per bar
909
+ for (const bar of history) {
910
+ rsi.step(bar.close);
911
+ bands.step(bar.close);
912
+ rsi.commit();
913
+ bands.commit();
914
+ }
915
+ // forming bar: a step per tick, a commit when the bar closes
916
+ onTick((price) => {
917
+ const value = rsi.step(price);
918
+ const [basis, upper, lower] = bands.step(price);
919
+ });
920
+ onBarClose(() => {
921
+ rsi.commit();
922
+ bands.commit();
923
+ });
924
+ ```
925
+
926
+ Available: `sum`, `sma`, `variance`, `stdev`, `wma`, `highest`, `lowest` (step with `(value, length)`, a series
927
+ length allowed), `ema`, `rma`, `change`, `mom`, `roc`, `rsi`, `cum`, `barssince`, `valuewhen`, `crossover`, `crossunder`,
928
+ `cross`, `tr`, `atr`, `obv`, `macd`, `bb`, `vwma`, `stoch`, `hma`, `dev`, `cci`, `mfi`, `dmi`, `linreg` (called on every
929
+ bar), `percentrank`, `median`, `correlation`, `wpr`, `supertrend`.
930
+
931
+ ### Strategies (strategy declaration and strategy.* API)
932
+
933
+ OakScriptJS does not fill orders. `strategy()` declares the strategy and its properties, and the
934
+ `strategy.*` calls and variables are forwarded to an order engine that the host supplies. The strategy
935
+ logic runs in `strategy.eachBar(fn)`: on each bar the engine fills the pending orders
936
+ (`processBar(i)`), the callback runs at the bar close, then the engine gets `processClose(i)`.
937
+
938
+ ```typescript
939
+ import { strategy, ta, close } from 'oakscriptjs/script';
940
+
941
+ strategy('MA Cross', {
942
+ initial_capital: 10000,
943
+ default_qty_type: strategy.percent_of_equity,
944
+ default_qty_value: 100,
945
+ });
946
+ const up = ta.crossover(ta.sma(close, 9), ta.sma(close, 21));
947
+ strategy.eachBar((c) => {
948
+ if (c.get(up) && strategy.position_size === 0) {
949
+ strategy.entry('L', strategy.long);
950
+ strategy.exit('X', { from_entry: 'L', stop: c.close * 0.95, limit: c.close * 1.15 });
951
+ }
952
+ });
953
+ ```
954
+
955
+ The host passes the engine to `executeScript(body, bars, inputs, chart, { strategyEngine })`. The
956
+ factory receives the resolved properties (declared values, else the PineScript defaults), the bars and
957
+ the chart context, and returns an object that implements `StrategyEngine`. The run result has the
958
+ properties in `strategyConfig`.
959
+
960
+ - Order options use the PineScript argument names (`from_entry`, `qty_percent`, `trail_points`...). An
961
+ `na` (NaN) option is removed before the call; the deprecated `when` argument does not exist.
962
+ - Order calls must be inside `strategy.eachBar()`, and so must the reads of per-bar values
963
+ (`strategy.position_size`, `strategy.equity`, `strategy.opentrade(i)`, `strategy.default_entry_qty()`...):
964
+ outside the loop they throw, because the engine's final state would be a future value for the earlier
965
+ bars. `strategy.initial_capital` and `strategy.account_currency` do not change and can be read anywhere.
966
+ - `strategy.opentrades.entry_price(i)` is written `strategy.opentrade(i)?.entry_price`, and
967
+ `strategy.closedtrades.profit(i)` is written `strategy.closedtrade(i)?.profit`.
968
+ - A variable, `strategy.risk.*` rule or `strategy.default_entry_qty()` that the engine does not provide
969
+ throws an error.
970
+
971
+ ---
972
+
973
+ ## API Reference
974
+
975
+ ### Core Namespaces
976
+
977
+ #### taCore (Technical Analysis - Array-based)
978
+
979
+ ```typescript
980
+ import {taCore} from 'oakscriptjs';
981
+
982
+ // Moving Averages
983
+ taCore.sma(source: number[], length: number): number[]
984
+ taCore.ema(source: number[], length: number): number[]
985
+ taCore.wma(source: number[], length: number): number[]
986
+
987
+ // Oscillators
988
+ taCore.rsi(source: number[], length: number): number[]
989
+ taCore.cci(source: number[], length: number): number[]
990
+
991
+ // MACD (returns tuple)
992
+ taCore.macd(
993
+ source: number[],
994
+ fastLength: number,
995
+ slowLength: number,
996
+ signalLength: number
997
+ ): [number[], number[], number[]]
998
+
999
+ // Bollinger Bands (returns tuple)
1000
+ taCore.bb(
1001
+ source: number[],
1002
+ length: number,
1003
+ mult: number
1004
+ ): [number[], number[], number[]] // [upper, basis, lower]
1005
+ ```
1006
+
1007
+ #### ta (Technical Analysis - Series-based)
1008
+
1009
+ ```typescript
1010
+ import {ta} from 'oakscriptjs';
1011
+
1012
+ // All functions accept Series and return Series
1013
+ ta.sma(source: Series, length: number): Series
1014
+ ta.ema(source: Series, length: number): Series
1015
+ ta.rsi(source: Series, length: number): Series
1016
+ ta.macd(source: Series, fast: number, slow: number, signal: number): [Series, Series, Series]
1017
+ ta.bb(source: Series, length: number, mult: number): [Series, Series, Series]
1018
+ ```
1019
+
1020
+ #### Series Class
1021
+
1022
+ ```typescript
1023
+ class Series {
1024
+ constructor(data: Bar[] | BarData, extractor: SeriesExtractor)
1025
+
1026
+ // Access underlying data
1027
+ get bars(): Bar[]
1028
+ get barData(): BarData
1029
+
1030
+ // Arithmetic
1031
+ add(other: Series | number): Series
1032
+ sub(other: Series | number): Series
1033
+ mul(other: Series | number): Series
1034
+ div(other: Series | number): Series
1035
+ mod(other: Series | number): Series
1036
+ neg(): Series
1037
+
1038
+ // Comparison (returns 1/0 series)
1039
+ gt(other: Series | number): Series
1040
+ lt(other: Series | number): Series
1041
+ gte(other: Series | number): Series
1042
+ lte(other: Series | number): Series
1043
+ eq(other: Series | number): Series
1044
+ neq(other: Series | number): Series
1045
+
1046
+ // Logical
1047
+ and(other: Series | number): Series
1048
+ or(other: Series | number): Series
1049
+ not(): Series
1050
+
1051
+ // Access
1052
+ get(index: number): number
1053
+ last(): number
1054
+ toArray(): number[]
1055
+
1056
+ // History
1057
+ offset(n: number): Series // Like close[1] in PineScript
1058
+
1059
+ // Memory management
1060
+ materialize(): Series // Break closure chains for memory efficiency
1061
+ }
1062
+ ```
1063
+
1064
+ #### BarData Class
1065
+
1066
+ ```typescript
1067
+ class BarData {
1068
+ constructor(bars: Bar[])
1069
+
1070
+ // Properties
1071
+ get version(): number // Current version number
1072
+ get bars(): Bar[] // Underlying bar array
1073
+ get length(): number // Number of bars
1074
+
1075
+ // Mutation methods (increment version)
1076
+ push(bar: Bar): void
1077
+ pop(): Bar | undefined
1078
+ set(index: number, bar: Bar): void
1079
+ updateLast(bar: Bar): void
1080
+ setAll(bars: Bar[]): void
1081
+ invalidate(): void // Manual version increment
1082
+
1083
+ // Access
1084
+ at(index: number): Bar | undefined
1085
+
1086
+ // Factory
1087
+ static from(bars: Bar[]): BarData
1088
+ }
1089
+ ```
1090
+
1091
+ #### LightweightChartsAdapter
1092
+
1093
+ `ChartAdapter` for lightweight-charts v5, used by the global-context runtime (`setContext`, `plot`, `hline`).
1094
+ OakScriptJS does not import lightweight-charts: pass the library's series definitions.
1095
+
1096
+ ```typescript
1097
+ import { createChart, CandlestickSeries, LineSeries, HistogramSeries } from 'lightweight-charts';
1098
+ import { LightweightChartsAdapter } from 'oakscriptjs';
1099
+
1100
+ const chart = createChart(container);
1101
+ const candles = chart.addSeries(CandlestickSeries);
1102
+ const adapter = new LightweightChartsAdapter(chart, { LineSeries, HistogramSeries }, candles);
1103
+ adapter.addSeries('histogram', { color: '#26a69a', pane: 1 }); // pane: lightweight-charts pane index
1104
+ ```
1105
+
1106
+ `LineSeries` is required; `HistogramSeries`, `AreaSeries`, `BaselineSeries` and `BarSeries` are needed only for
1107
+ those series types.
1108
+
1109
+ #### Metadata Types
1110
+
1111
+ ```typescript
1112
+ import type {
1113
+ IndicatorResult,
1114
+ IndicatorMetadata,
1115
+ PlotData,
1116
+ PlotOptions,
1117
+ HLineData,
1118
+ HLineOptions,
1119
+ FillData,
1120
+ InputMetadata
1121
+ } from 'oakscriptjs';
1122
+
1123
+ interface IndicatorResult {
1124
+ metadata: IndicatorMetadata;
1125
+ plots: Record<string, TimeValue[]>; // keyed by plot id
1126
+ hlines?: HLineData[];
1127
+ fills?: FillData[];
1128
+ markers?: MarkerData[]; // from plotshape() / plotchar()
1129
+ arrows?: ArrowData[]; // from plotarrow()
1130
+ bgColors?: BgColorData[]; // from bgcolor()
1131
+ barColors?: BarColorData[]; // from barcolor()
1132
+ plotCandles?: Record<string, PlotCandleData[]>; // from plotcandle()
1133
+ plotBars?: Record<string, PlotBarData[]>; // from plotbar()
1134
+ labels?: LabelData[]; // live drawings after the last bar
1135
+ lines?: LineDrawingData[];
1136
+ boxes?: BoxData[];
1137
+ linefills?: LinefillData[];
1138
+ polylines?: PolylineData[];
1139
+ tables?: TableData[];
1140
+ }
1141
+ ```
1142
+
1143
+ ---
1144
+
1145
+ ## Examples
1146
+
1147
+ ### Example 1: Simple Moving Average (script API)
1148
+
1149
+ ```typescript
1150
+ import { executeScript, indicator, input, plot, ta, color, close } from 'oakscriptjs/script';
1151
+
1152
+ function smaIndicator() {
1153
+ indicator('SMA 20', { overlay: true });
1154
+ const length = input.int(20, 'Length', { minval: 1 });
1155
+ plot(ta.sma(close, length), 'SMA', { color: color.blue, linewidth: 2 });
1156
+ }
1157
+
1158
+ const run = executeScript(smaIndicator, bars);
1159
+ // run.result.plots['plot0'] → [{ time, value }, ...] (warm-up NaNs filtered out)
1160
+ ```
1161
+
1162
+ ### Example 2: Balance of Power (script API)
1163
+
1164
+ ```typescript
1165
+ import { executeScript, indicator, plot, hline, color, open, high, low, close } from 'oakscriptjs/script';
1166
+
1167
+ function bopIndicator() {
1168
+ indicator('Balance of Power', { overlay: false });
1169
+ const bop = close.sub(open).div(high.sub(low)); // (close - open) / (high - low)
1170
+ plot(bop, 'BOP', { color: color.red, linewidth: 2 });
1171
+ hline(0, 'Zero', { color: color.gray });
1172
+ }
1173
+
1174
+ const run = executeScript(bopIndicator, bars);
1175
+ ```
1176
+
1177
+ ### Example 3: Low-level array API (no chart)
1178
+
1179
+ ```typescript
1180
+ import { taCore } from 'oakscriptjs';
1181
+
1182
+ const closes = bars.map((b) => b.close);
1183
+ const sma = taCore.sma(closes, 20); // number[]
1184
+ const rsi = taCore.rsi(closes, 14); // number[]
1185
+ ```