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