@tradecanvas/script 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,120 +1,126 @@
1
- # @tradecanvas/script
2
-
3
- Indicators written bar by bar for [TradeCanvas](https://tradecanvas.dev/): state kept from bar to bar, past values read back, `ta` sums that run one bar at a time, and a live bar run again on each tick.
4
-
5
- Not published yet: the package is being built in steps, and its API can still change.
6
-
7
- ```ts
8
- import { defineScript, scriptIndicator, ta } from '@tradecanvas/script';
9
-
10
- const emaCross = defineScript({
11
- id: 'emaCross',
12
- name: 'EMA Cross',
13
- overlay: true,
14
- inputs: { fast: { default: 9, kind: 'int', min: 1 }, slow: { default: 21, kind: 'int', min: 1 } },
15
- setup({ inputs, plot, shape }) {
16
- const fast = ta.ema(inputs.fast);
17
- const slow = ta.ema(inputs.slow);
18
- const up = ta.crossover();
19
- const fastLine = plot('Fast', { color: '#f5c542' });
20
- const slowLine = plot('Slow', { color: '#3b82f6' });
21
- const mark = shape('Cross up', { shape: 'triangleUp', position: 'belowBar', color: '#22c55e' });
22
- return (bar) => {
23
- const f = fastLine.set(fast(bar.close));
24
- const s = slowLine.set(slow(bar.close));
25
- mark.set(up(f, s));
26
- };
27
- },
28
- });
29
-
30
- chart.registerIndicator(scriptIndicator(emaCross));
31
- chart.addIndicator('emaCross');
32
- ```
33
-
34
- ## How it runs
35
-
36
- - `setup` runs once: it declares the plots, marks and levels, makes the `ta` sums and the kept state (`state.var`, `state.array`, `state.series`), and returns what each bar runs.
37
- - Each `ta` sum keeps its own state: two calls of `ta.ema(9)` are two averages. Make them in `setup`, never on a bar. Their values are the chart's built-in indicators' (the MACD's averages start as simple ones).
38
- - The closed bars run once. The last bar stays live: a tick runs it again from the state the bar before left, so a tick costs one bar.
39
- - `ScriptRun` runs a script without a chart (`load`, `tick`, `next`, `update`); its output is a typed array a plot. `new ScriptRun(script, params, { exchangeTimeZone, sessionStart })` counts days on the exchange's clock.
40
- - Only what the script keeps through `state` and the `ta` sums is put back before a tick. A plain `let` in `setup` is not: keep values in `state.var`.
41
- - Feed each `ta` sum on every bar for the values the chart's indicators have: a sum fed on some bars only averages those bars.
42
- - A missing value (NaN) is handled as `@tradecanvas/core`'s `ta` handles it: a simple or weighted average needs its period of numbers in a row, a smoothing skips it, and RSI, MACD, the bands, HMA, ROC and momentum compute over it as the last value and give none there.
43
- - `ta.macd`'s averages start as simple ones, like every EMA here; the chart's built-in MACD starts its own at the first close, so their first hundred bars or so differ by a hair.
44
- - A bar that throws stops the script there; `output.errors` (`meta.errors` of the indicator's output) says which bar and why. A tick on the live bar runs it again; once that bar closes, the script stays stopped until the bars are loaded again.
45
-
46
- ## The ta sums
47
-
48
- Each is made in `setup` with its settings, then given a value each bar.
49
-
50
- - Averages: `sma`, `ema`, `rma`, `wma`, `vwma` (value, volume), `hma`, `alma(period, offset, sigma)`, `swma` (four values, weighted 1, 2, 2, 1), `linreg(period, offset)`.
51
- - Over a window: `sum`, `stdev`, `variance`, `dev` (mean distance from the mean), `median`, `percentileNearestRank(period, percentage)`, `percentileLinearInterpolation(period, percentage)`, `percentrank` (the share of the bars before at or under this one), `correlation` (two values), `highest`, `lowest`, `highestbars` and `lowestbars` (how many bars back the extreme is, 0 or less).
52
- - Running: `cum` (the total so far), `change`, `mom`, `roc`, `barssince`, `valuewhen`.
53
- - Oscillators: `rsi`, `macd`, `bb`, `stoch` (value, high, low: the raw %K), `mfi` (value, volume).
54
- - Of the bars: `tr`, `atr`, `supertrend`, `sar(start, increment, max)`, `obv` (close, volume).
55
- - Events: `crossover`, `crossunder`, `cross`, `rising(period)` and `falling(period)` (over, or under, every one of the bars before), `pivothigh`, `pivotlow`.
56
-
57
- ALMA, `linreg`, the stochastic, MFI, OBV and `sar` give the values of the built-in indicators (ALMA, LSMA, Stochastic, MFI, OBV, Parabolic SAR); `sar` starts on the second bar, its first trend read from the first two closes. A window with a missing value in it gives none; `cum` passes over one.
58
-
59
- `bar.live` is true on the live bar, the last one, which a tick runs again.
60
-
61
- ## Colours, fills, backgrounds
62
-
63
- - `plot.set(value, color)` gives a bar its own colour; the line's stretch to that bar takes it.
64
- - `fill(plotA, plotB, { color })` shades between two plots; `.set(color)` gives a bar its own colour. A colour with an alpha of its own (`'#22c55e33'`) keeps it.
65
- - `bgcolor()` returns a background: `.set(color)` shades the pane behind that bar, behind the candles and the levels.
66
- - `plot(title, { kind: 'area' })` shades the space down to zero under the line.
67
- - `barcolor()` returns a handle: `.set(color)` paints that bar's candle, in a script drawn over the prices (`overlay: true`), on a chart of candles or OHLC bars.
68
- - `shape(title, { position: 'top' })` marks the top or the bottom of the pane; in a pane of its own, `'aboveBar'` and `'belowBar'` are the top and the bottom.
69
-
70
- ## Labels, lines and boxes
71
-
72
- `drawings({ maxLabels, maxLines, maxBoxes })` in `setup` gives a list to draw on: on a bar, `label({ at, text })`, `line({ from, to, extend })` and `box({ from, to, fill })` each return a handle to `set()` or `remove()` later. A point is `{ bar, value }`, `bar` being a bar's index (`bar.index - 5`). Past a kind's limit (50 unless set, 500 at most) the oldest goes. Keep a handle across bars in `state.var`, so a tick puts it back with the shapes.
73
-
74
- ## Alerts
75
-
76
- `alertCondition(title, { message })` in `setup` says a moment (`.set(true)` on the bars it holds). The widget's alert form lists it as "<name>: <title>", and an alert set on it fires as it turns true.
77
-
78
- ## Higher intervals
79
-
80
- `request.security('1h', () => { const avg = ta.sma(20); return (bar) => avg(bar.close); })` in `setup` gives a function to call on every bar: the value of that interval's bars, made of the chart's own (a resample of them, days cut on the exchange's clock). A bar reads the value of the last bar of the higher interval that closed before its own, which never changes after; with `{ live: true }`, the forming bar's as it was then, which repaints. Neither reads a bar after the chart's own. Same symbol only, for now.
81
-
82
- ## Levels
83
-
84
- `hline(70, { color: '#ef4444', lineStyle: 'solid', title: 'Overbought' })` in `setup` draws a level across the pane in a colour and dash of its own; without a colour it is faint and dashed, as the chart's levels are. The title is not drawn.
85
-
86
- ## Limits
87
-
88
- A run stops a script at the bar that goes past one of its limits, and says which in `errors` (`limit: 'loop' | 'array' | 'time'`):
89
-
90
- - **Loop steps**: `loop()`, called once each time round a loop, counts the bar's steps; past a million (`loopSteps`) the bar stops, so a loop that never ends does not hang the chart.
91
- - **Lists**: a `state.array` holds at most 100,000 numbers (`arraySize`). A list that takes a number every bar and is never cut needs a larger `arraySize` on a longer chart, or a `shift()` to keep it short.
92
- - **Time**: with `runMs` set, a `load`, `tick` or `next` that is past that many ms after a bar stops there.
93
-
94
- Set them with `new ScriptRun(script, params, { limits: { loopSteps: 10_000, runMs: 200 } })`, or `scriptIndicator(script, { limits })`. A higher interval's run keeps to the same loop steps and list sizes; its time counts in the script's. A script that catches the error and goes on is stopped all the same. A bar that never returns, a loop without `loop()`, is not stopped on the page's thread: that needs a worker.
95
-
96
- ## In a worker
97
-
98
- A script can run in a worker, so a bar that never returns cannot hang the page. The worker's module serves the scripts, and the page registers each through `scriptWorkerIndicator`:
99
-
100
- ```ts
101
- // scripts.worker.ts
102
- import { serveScripts } from '@tradecanvas/script'
103
- import { emaCross } from './emaCross'
104
- serveScripts([emaCross])
105
-
106
- // the page
107
- chart.registerIndicator(scriptWorkerIndicator(emaCross, {
108
- spawn: () => new Worker(new URL('./scripts.worker.ts', import.meta.url), { type: 'module' }),
109
- timeoutMs: 5000,
110
- }))
111
- ```
112
-
113
- The page sends the bars once, then one bar a tick, and draws the points the worker sends back from that bar on; until the first answer the indicator draws nothing. A worker that does not answer one request within `timeoutMs` (5 seconds unless set, the first load of the bars included) is stopped: the script it hung on says so (`limit: 'time'`) and loads again only for other inputs or other bars; the others load again in a new worker. A removed indicator's run goes with it, and the worker once it runs nothing. The setup also runs once on the page, to know what the script draws. `limits` are passed on to the worker's runs.
114
-
115
- ## Not there yet
116
-
117
- - Other symbols in `request.security`.
118
- - Pine Script source: a compiler to these scripts is planned.
119
-
120
- The guide: [tradecanvas.dev/docs/scripts](https://tradecanvas.dev/docs/scripts).
1
+ # @tradecanvas/script
2
+
3
+ Indicators written bar by bar for [TradeCanvas](https://tradecanvas.dev/): state kept from bar to bar, past values read back, `ta` sums that run one bar at a time, and a live bar run again on each tick.
4
+
5
+ ```bash
6
+ npm install @tradecanvas/script @tradecanvas/chart
7
+ ```
8
+
9
+ Before 1.0, its API can still change between minor versions.
10
+
11
+ ```ts
12
+ import { defineScript, scriptIndicator, ta } from '@tradecanvas/script';
13
+
14
+ const emaCross = defineScript({
15
+ id: 'emaCross',
16
+ name: 'EMA Cross',
17
+ overlay: true,
18
+ inputs: { fast: { default: 9, kind: 'int', min: 1 }, slow: { default: 21, kind: 'int', min: 1 } },
19
+ setup({ inputs, plot, shape }) {
20
+ const fast = ta.ema(inputs.fast);
21
+ const slow = ta.ema(inputs.slow);
22
+ const up = ta.crossover();
23
+ const fastLine = plot('Fast', { color: '#f5c542' });
24
+ const slowLine = plot('Slow', { color: '#3b82f6' });
25
+ const mark = shape('Cross up', { shape: 'triangleUp', position: 'belowBar', color: '#22c55e' });
26
+ return (bar) => {
27
+ const f = fastLine.set(fast(bar.close));
28
+ const s = slowLine.set(slow(bar.close));
29
+ mark.set(up(f, s));
30
+ };
31
+ },
32
+ });
33
+
34
+ chart.registerIndicator(scriptIndicator(emaCross));
35
+ chart.addIndicator('emaCross');
36
+ ```
37
+
38
+ ## How it runs
39
+
40
+ - `setup` runs once: it declares the plots, marks and levels, makes the `ta` sums and the kept state (`state.var`, `state.array`, `state.series`), and returns what each bar runs.
41
+ - Each `ta` sum keeps its own state: two calls of `ta.ema(9)` are two averages. Make them in `setup`, never on a bar. Their values are the chart's built-in indicators' (the MACD's averages start as simple ones).
42
+ - The closed bars run once. The last bar stays live: a tick runs it again from the state the bar before left, so a tick costs one bar. When a new bar comes, the live one runs once more as a closed bar (`bar.live` false), so a feed ends where loading its bars does.
43
+ - `ScriptRun` runs a script without a chart (`load`, `tick`, `next`, `update`); its output is a typed array a plot. `new ScriptRun(script, params, { exchangeTimeZone, sessionStart })` counts days on the exchange's clock.
44
+ - Only what the script keeps through `state` and the `ta` sums is put back before a bar runs again (a tick, or the bar closing). A plain `let` in `setup` is not: keep values in `state.var`.
45
+ - Feed each `ta` sum on every bar for the values the chart's indicators have: a sum fed on some bars only averages those bars.
46
+ - A missing value (NaN) is handled as `@tradecanvas/core`'s `ta` handles it: a simple or weighted average needs its period of numbers in a row, a smoothing skips it, and RSI, MACD, the bands, HMA, ROC and momentum compute over it as the last value and give none there.
47
+ - `ta.macd`'s averages start as simple ones, like every EMA here; the chart's built-in MACD starts its own at the first close, so their first hundred bars or so differ by a hair.
48
+ - A bar that throws stops the script there; `output.errors` (`meta.errors` of the indicator's output) says which bar and why. A tick on the live bar runs it again; once that bar closes, the script stays stopped until the bars are loaded again.
49
+
50
+ ## The ta sums
51
+
52
+ Each is made in `setup` with its settings, then given a value each bar.
53
+
54
+ - Averages: `sma`, `ema`, `rma`, `wma`, `vwma` (value, volume), `hma`, `alma(period, offset, sigma)`, `swma` (four values, weighted 1, 2, 2, 1), `linreg(period, offset)`.
55
+ - Over a window: `sum`, `stdev`, `variance`, `dev` (mean distance from the mean), `median`, `percentileNearestRank(period, percentage)`, `percentileLinearInterpolation(period, percentage)`, `percentrank` (the share of the bars before at or under this one), `correlation` (two values), `highest`, `lowest`, `highestbars` and `lowestbars` (how many bars back the extreme is, 0 or less).
56
+ - Running: `cum` (the total so far), `change`, `mom`, `roc`, `barssince`, `valuewhen`.
57
+ - Oscillators: `rsi`, `macd`, `bb`, `stoch` (value, high, low: the raw %K), `mfi` (value, volume).
58
+ - Of the bars: `tr`, `atr`, `supertrend`, `sar(start, increment, max)`, `obv` (close, volume).
59
+ - Events: `crossover`, `crossunder`, `cross`, `rising(period)` and `falling(period)` (over, or under, every one of the bars before), `pivothigh`, `pivotlow`.
60
+
61
+ ALMA, `linreg`, the stochastic, MFI, OBV and `sar` give the values of the built-in indicators (ALMA, LSMA, Stochastic, MFI, OBV, Parabolic SAR); `sar` starts on the second bar, its first trend read from the first two closes. A window with a missing value in it gives none; `cum` passes over one.
62
+
63
+ `bar.live` is true on the live bar, the last one, which a tick runs again, and false once it closes.
64
+
65
+ `chart.timeZone` in `setup` is the exchange's zone (`'UTC'` when the chart names none) and `chart.interval` its interval (`'5m'`, null when not known): a script that reads the interval in `setup` is run again when it changes (what it declares, its plots and levels, may not depend on it), and any script is when the zone does. A run without a chart is told by its options, `new ScriptRun(script, params, { exchangeTimeZone, interval })`.
66
+
67
+ ## Colours, fills, backgrounds
68
+
69
+ - `plot.set(value, color)` gives a bar its own colour; the line's stretch to that bar takes it.
70
+ - `fill(plotA, plotB, { color })` shades between two plots; `.set(color)` gives a bar its own colour. A colour with an alpha of its own (`'#22c55e33'`) keeps it.
71
+ - `bgcolor()` returns a background: `.set(color)` shades the pane behind that bar, behind the candles and the levels.
72
+ - `plot(title, { kind: 'area' })` shades the space down to zero under the line.
73
+ - `barcolor()` returns a handle: `.set(color)` paints that bar's candle, in a script drawn over the prices (`overlay: true`), on a chart of candles or OHLC bars.
74
+ - `shape(title, { position: 'top' })` marks the top or the bottom of the pane; in a pane of its own, `'aboveBar'` and `'belowBar'` are the top and the bottom.
75
+
76
+ ## Labels, lines and boxes
77
+
78
+ `drawings({ maxLabels, maxLines, maxBoxes })` in `setup` gives a list to draw on: on a bar, `label({ at, text })`, `line({ from, to, extend })` and `box({ from, to, fill })` each return a handle to `set()` or `remove()` later. A point is `{ bar, value }`, `bar` being a bar's index (`bar.index - 5`). Past a kind's limit (50 unless set, 500 at most) the oldest goes. Keep a handle across bars in `state.var`, so a tick puts it back with the shapes.
79
+
80
+ ## Alerts
81
+
82
+ `alertCondition(title, { message })` in `setup` says a moment (`.set(true)` on the bars it holds). The widget's alert form lists it as "<name>: <title>", and an alert set on it fires as it turns true.
83
+
84
+ ## Higher intervals
85
+
86
+ `request.security('1h', () => { const avg = ta.sma(20); return (bar) => avg(bar.close); })` in `setup` gives a function to call on every bar: the value of that interval's bars, made of the chart's own (a resample of them, days cut on the exchange's clock). A bar reads the value of the last bar of the higher interval that closed before its own, which never changes after; with `{ live: true }`, the forming bar's as it was then, which repaints. Neither reads a bar after the chart's own. Same symbol only, for now.
87
+
88
+ ## Levels
89
+
90
+ `hline(70, { color: '#ef4444', lineStyle: 'solid', title: 'Overbought' })` in `setup` draws a level across the pane in a colour and dash of its own; without a colour it is faint and dashed, as the chart's levels are. The title is not drawn.
91
+
92
+ ## Limits
93
+
94
+ A run stops a script at the bar that goes past one of its limits, and says which in `errors` (`limit: 'loop' | 'array' | 'time'`):
95
+
96
+ - **Loop steps**: `loop()`, called once each time round a loop, counts the bar's steps; past a million (`loopSteps`) the bar stops, so a loop that never ends does not hang the chart.
97
+ - **Lists**: a `state.array` holds at most 100,000 numbers (`arraySize`). A list that takes a number every bar and is never cut needs a larger `arraySize` on a longer chart, or a `shift()` to keep it short.
98
+ - **Time**: with `runMs` set, a `load`, `tick` or `next` that is past that many ms after a bar stops there.
99
+
100
+ Set them with `new ScriptRun(script, params, { limits: { loopSteps: 10_000, runMs: 200 } })`, or `scriptIndicator(script, { limits })`. A higher interval's run keeps to the same loop steps and list sizes; its time counts in the script's. A script that catches the error and goes on is stopped all the same. A bar that never returns, a loop without `loop()`, is not stopped on the page's thread: that needs a worker.
101
+
102
+ ## In a worker
103
+
104
+ A script can run in a worker, so a bar that never returns cannot hang the page. The worker's module serves the scripts, and the page registers each through `scriptWorkerIndicator`:
105
+
106
+ ```ts
107
+ // scripts.worker.ts
108
+ import { serveScripts } from '@tradecanvas/script'
109
+ import { emaCross } from './emaCross'
110
+ serveScripts([emaCross])
111
+
112
+ // the page
113
+ chart.registerIndicator(scriptWorkerIndicator(emaCross, {
114
+ spawn: () => new Worker(new URL('./scripts.worker.ts', import.meta.url), { type: 'module' }),
115
+ timeoutMs: 5000,
116
+ }))
117
+ ```
118
+
119
+ The page sends the bars once, then one bar a tick, and draws the points the worker sends back from that bar on; until the first answer the indicator draws nothing. A worker that does not answer one request within `timeoutMs` (5 seconds unless set, the first load of the bars included) is stopped: the script it hung on says so (`limit: 'time'`) and loads again only for other inputs or other bars; the others load again in a new worker. A removed indicator's run goes with it, and the worker once it runs nothing. The setup also runs once on the page, to know what the script draws. `limits` are passed on to the worker's runs.
120
+
121
+ ## Not there yet
122
+
123
+ - Other symbols in `request.security`.
124
+ - Pine Script source: a compiler to these scripts is planned.
125
+
126
+ The guide: [tradecanvas.dev/docs/scripts](https://tradecanvas.dev/docs/scripts).
@@ -1,4 +1,4 @@
1
- import { OHLCBar } from '@tradecanvas/commons';
1
+ import { OHLCBar, TimeFrame } from '@tradecanvas/commons';
2
2
  import { Script, ScriptInputs } from './defineScript.js';
3
3
  import { ScriptDeclarations, ScriptError, ScriptOutput } from './outputs.js';
4
4
  import { ScriptLimits } from './limits.js';
@@ -8,6 +8,8 @@ export interface ScriptRunOptions {
8
8
  exchangeTimeZone?: string;
9
9
  /** Minutes after midnight the trading day starts at (a 17:00 open: 1020); unset: midnight. */
10
10
  sessionStart?: number;
11
+ /** The chart's interval (`'5m'`), which the script may read; unset: not known. */
12
+ interval?: TimeFrame;
11
13
  /** How far the run may go: loop steps a bar, numbers a list, ms a run. */
12
14
  limits?: ScriptLimits;
13
15
  }
@@ -40,6 +42,7 @@ export declare class ScriptRun {
40
42
  private readonly limits;
41
43
  /** When the `load`, `tick` or `next` running began, by `performance.now()`. */
42
44
  private began;
45
+ private intervalRead;
43
46
  constructor(script: Script<ScriptInputs>, params?: Readonly<Record<string, unknown>>, options?: ScriptRunOptions);
44
47
  /** Where the script stopped, and why: none while it runs. */
45
48
  get errors(): readonly ScriptError[];
@@ -51,17 +54,24 @@ export declare class ScriptRun {
51
54
  /** The live bar as it now is: run it again from the state the bar before left. */
52
55
  tick(bar: OHLCBar): void;
53
56
  /**
54
- * Close the live bar as it last ran, and run `bar` as the new live one. A
55
- * script that threw on the live bar stays stopped once it closes, as on
56
- * any closed bar: load the bars again to run it anew.
57
+ * Close the live bar, run once more as a closed one (`bar.live` false) so
58
+ * a feed ends where loading its bars does, and run `bar` as the new live
59
+ * one. A script that threw on the live bar stays stopped once it closes,
60
+ * as on any closed bar: load the bars again to run it anew.
57
61
  */
58
62
  next(bar: OHLCBar): void;
59
63
  /** A bar from a feed: a tick when it has the live bar's time, a new bar when later. An earlier one is not run: load the bars again. */
60
64
  update(bar: OHLCBar): UpdateKind;
61
65
  /** Begin again from no bars: a new setup, new state. */
62
66
  private start;
67
+ /** The chart as the script reads it, noting that the interval was. */
68
+ private chart;
69
+ /** Whether the script has read the chart's interval: in its setup, for one that has run no bar. */
70
+ get readsInterval(): boolean;
63
71
  /** From here on the bar run is the live one: keep the state the bars before left. */
64
72
  private goLive;
73
+ /** The live bar as it closed: run from the state the bar before left, as the closed bar it now is. */
74
+ private closeLive;
65
75
  private priceSeries;
66
76
  private write;
67
77
  /** Bar `i` as its prices now stand. */
@@ -1 +1 @@
1
- {"version":3,"file":"ScriptRun.d.ts","sourceRoot":"","sources":["../src/ScriptRun.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAEpD,OAAO,EAA4C,KAAK,MAAM,EAAkB,KAAK,YAAY,EAAqB,MAAM,mBAAmB,CAAC;AAChJ,OAAO,EAAW,KAAK,kBAAkB,EAAE,KAAK,WAAW,EAAE,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC;AAKrG,OAAO,EAAyC,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AAKvF,+EAA+E;AAC/E,MAAM,WAAW,gBAAgB;IAC/B,mEAAmE;IACnE,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,8FAA8F;IAC9F,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,0EAA0E;IAC1E,MAAM,CAAC,EAAE,YAAY,CAAC;CACvB;AAED,2HAA2H;AAC3H,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAC;AAEnD;;;;GAIG;AACH,qBAAa,SAAS;IAyBlB,OAAO,CAAC,QAAQ,CAAC,MAAM;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C,MAAM;IAuBd,8EAA8E;IAC9E,OAAO,CAAC,OAAO;IAIf,oEAAoE;IACpE,OAAO,CAAC,QAAQ;CAKjB"}
@@ -25,7 +25,8 @@ export interface ScriptBar {
25
25
  readonly volume: number;
26
26
  /**
27
27
  * The live bar: the last, run again on each tick until the next bar
28
- * comes. False on the bars that closed before it.
28
+ * comes. False on the bars that closed, the live one too when the next
29
+ * bar comes: it is run once more as it closes.
29
30
  */
30
31
  readonly live: boolean;
31
32
  }
@@ -107,9 +108,21 @@ export interface HlineOptions {
107
108
  /** Its name: not drawn, and not shown in the indicator settings yet. */
108
109
  title?: string;
109
110
  }
111
+ /** The chart a script runs on. */
112
+ export interface ScriptChart {
113
+ /** The exchange's IANA zone (`'Asia/Ho_Chi_Minh'`); `'UTC'` when the chart names none. */
114
+ readonly timeZone: string;
115
+ /**
116
+ * The chart's interval (`'5m'`, `'1d'`), null when it is not known. Read
117
+ * it in setup: the script is then run again when it changes. What a
118
+ * script declares (its plots, inputs, levels) may not depend on it.
119
+ */
120
+ readonly interval: TimeFrame | null;
121
+ }
110
122
  /** What a script's setup is given to declare what it draws and keeps. */
111
123
  export interface ScriptSetup<V> {
112
124
  readonly inputs: V;
125
+ readonly chart: ScriptChart;
113
126
  /** The bars' prices, read back from the bar being run (`prices.close.at(1)`). */
114
127
  readonly prices: ScriptPrices;
115
128
  /** A value a bar drawn as a line, histogram, dots or steps. */
@@ -1 +1 @@
1
- {"version":3,"file":"defineScript.d.ts","sourceRoot":"","sources":["../src/defineScript.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACrF,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACjE,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACnE,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,eA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MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,UAAU,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAIvH;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,WAAW,GAAG,gBAAgB,CAW7E"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const pt=require("@tradecanvas/commons"),B=require("@tradecanvas/core");function Nt(n){if(typeof n.id!="string"||n.id.trim()==="")throw new Error("defineScript: a script needs an id");if(typeof n.setup!="function")throw new Error(`defineScript('${n.id}'): a script needs a setup function`);return Object.freeze({...n,kind:"script"})}function Kt(n,t){const e=t.default;if(typeof e=="number"){const s=typeof n=="string"&&n.trim()!==""?Number(n):n;if(typeof s!="number"||!Number.isFinite(s))return e;const r=t.kind==="int"?Math.floor(s):s;return Math.min(t.max??1/0,Math.max(t.min??-1/0,r))}return typeof n!=typeof e||t.options&&!t.options.some(s=>(typeof s=="object"?s.value:s)===n)?e:n}const zt=256;class Q{constructor(t,e){this.make=t,this.empty=e,this.data=t(zt),this.data.fill(e)}data;filled=0;set(t,e){this.reach(t+1),this.data[t]=e}get(t){return t>=0&&t<this.filled?this.data[t]:this.empty}reach(t){if(t>this.data.length){let e=this.data.length;for(;e<t;)e*=2;const s=this.make(e);s.fill(this.empty),s.set(this.data),this.data=s}t>this.filled&&(this.filled=t)}view(t){return this.reach(t),this.data.subarray(0,t)}}const q=()=>new Q(n=>new Float64Array(n),Number.NaN),_=()=>new Q(n=>new Uint16Array(n),0),it=()=>new Q(n=>new Uint8Array(n),0),ot=65535;class Dt{constructor(t){this.scope=t,t.clearers.push(e=>{for(const s of this.plots)s.values.set(e,Number.NaN),s.colors.set(e,0);for(const s of this.shapes)s.on.set(e,0);for(const s of this.fills)s.colors.set(e,0);for(const s of this.backgrounds)s.colors.set(e,0);for(const s of this.conditions)s.on.set(e,0);for(const s of this.barColorSlots)s.set(e,0)})}plots=[];handles=new Map;shapes=[];fills=[];backgrounds=[];conditions=[];barColorSlots=[];levels=[];drawingLists=[];palette=[];paletteIndex=new Map;open=!0;close(){this.open=!1}declaring(t){if(!this.open)throw new Error(`${t} is declared in the script's setup, not on a bar`)}colorIndex(t){let e=this.paletteIndex.get(t);if(e===void 0){if(this.palette.length>=ot)throw new Error(`a script gives its bars at most ${ot} colours`);this.palette.push(t),e=this.palette.length,this.paletteIndex.set(t,e)}return e}plot(t,e={}){this.declaring("plot");const s={declaration:{title:t,kind:e.kind??"line",...e.color?{color:e.color}:{},...e.width?{width:e.width}:{}},values:q(),colors:_()};this.plots.push(s);const r={set:(i,o)=>(s.values.set(this.scope.bar,Number.isFinite(i)?i:Number.NaN),o!==void 0&&s.colors.set(this.scope.bar,this.colorIndex(o)),i)};return this.handles.set(r,this.plots.length-1),r}shape(t,e={}){this.declaring("shape");const s={declaration:{title:t,shape:e.shape??"triangleUp",position:e.position??"belowBar",...e.color?{color:e.color}:{}},on:it()};return this.shapes.push(s),{set:r=>(s.on.set(this.scope.bar,r?1:0),r)}}fill(t,e,s={}){this.declaring("fill");const r=this.handles.get(t),i=this.handles.get(e);if(r===void 0||i===void 0)throw new Error("fill is between two plots of the same script");const o={declaration:{between:[r,i],...s.color?{color:s.color}:{}},colors:_()};return this.fills.push(o),{set:u=>{o.colors.set(this.scope.bar,u===void 0?0:this.colorIndex(u))}}}bgcolor(t={}){this.declaring("bgcolor");const e={declaration:{title:t.title??"Background"},colors:_()};return this.backgrounds.push(e),{set:s=>{e.colors.set(this.scope.bar,s===void 0?0:this.colorIndex(s))}}}addDrawings(t){return this.drawingLists.push(t),t}barcolor(){this.declaring("barcolor");const t=_();return this.barColorSlots.push(t),{set:e=>{t.set(this.scope.bar,e===void 0?0:this.colorIndex(e))}}}alertCondition(t,e={}){this.declaring("alertCondition");const s={declaration:{title:t,...e.message?{message:e.message}:{}},on:it()};return this.conditions.push(s),{set:r=>(s.on.set(this.scope.bar,r?1:0),r)}}hline(t,e={}){this.declaring("hline"),this.levels.push({price:t,...e})}declarations(t){return{overlay:t,plots:this.plots.map(e=>e.declaration),shapes:this.shapes.map(e=>e.declaration),levels:[...this.levels],fills:this.fills.map(e=>e.declaration),backgrounds:this.backgrounds.map(e=>e.declaration),barColors:this.barColorSlots.length,alertConditions:this.conditions.map(e=>e.declaration)}}output(t,e){return{length:t,plots:this.plots.map(s=>({...s.declaration,values:s.values.view(t),colors:s.colors.view(t)})),shapes:this.shapes.map(s=>({...s.declaration,on:s.on.view(t)})),levels:[...this.levels],fills:this.fills.map(s=>({...s.declaration,colors:s.colors.view(t)})),backgrounds:this.backgrounds.map(s=>({...s.declaration,colors:s.colors.view(t)})),barColors:this.barColorSlots.map(s=>s.view(t)),alertConditions:this.conditions.map(s=>({...s.declaration,on:s.on.view(t)})),palette:[...this.palette],drawings:this.drawingLists.flatMap(s=>s.list()),errors:[...e]}}}let F=null;function Pt(n,t){const e=F;F=n;try{return t()}finally{F=e}}function I(n="ta and state"){if(!F)throw new Error(`${n} are made in a script's setup, not on a bar: each keeps the state of one script`);return F}function b(n){const t={...n},e={...n};return I().units.push({commit:()=>Object.assign(e,t),rollback:()=>Object.assign(t,e)}),t}const Y={loopSteps:1e6,arraySize:1e5,runMs:Number.POSITIVE_INFINITY};class j extends Error{constructor(t,e){super(e),this.limit=t,this.name="ScriptLimitError"}}function tt(n={}){const t=Object.fromEntries(Object.entries(n).filter(([,s])=>s!==void 0)),e={...Y,...t};for(const s of Object.keys(Y)){const r=e[s];if(typeof r!="number"||Number.isNaN(r)||r<=0)throw new RangeError(`script limits: ${s} must be a positive number, not ${String(r)}`)}return e}function dt(n,t,e){const s=new j(t,e);throw n.breach??=s,s}function Ut(n){const t=I("state.var"),e={value:n};let s=n;return t.units.push({commit:()=>{s=e.value},rollback:()=>{e.value=s}}),e}function Zt(){const n=I("state.series"),t=q();return n.clearers.push(e=>t.set(e,Number.NaN)),{set:e=>(t.set(n.bar,e),e),at:(e=0)=>e>=0?t.get(n.bar-Math.floor(e)):Number.NaN}}class Vt{constructor(t){this.scope=t,t.units.push({commit:()=>{this.undo=[]},rollback:()=>{for(let e=this.undo.length-1;e>=0;e--)this.undo[e]();this.undo=[]}})}items=[];undo=[];record(t){this.scope.live&&this.undo.push(t)}grow(){const t=this.scope.limits.arraySize;this.items.length>=t&&dt(this.scope,"array",`a list holds at most ${t} numbers`)}size(){return this.items.length}get(t){const e=t<0?this.items.length+t:t;return e>=0&&e<this.items.length?this.items[e]:Number.NaN}set(t,e){if(t<0||t>=this.items.length)throw new RangeError(`array.set: index ${t} is outside a list of ${this.items.length}`);const s=this.items[t];this.items[t]=e,this.record(()=>{this.items[t]=s})}push(t){this.grow(),this.items.push(t),this.record(()=>{this.items.pop()})}pop(){if(this.items.length===0)return Number.NaN;const t=this.items.pop();return this.record(()=>{this.items.push(t)}),t}shift(){if(this.items.length===0)return Number.NaN;const t=this.items.shift();return this.record(()=>{this.items.unshift(t)}),t}unshift(t){this.grow(),this.items.unshift(t),this.record(()=>{this.items.shift()})}clear(){const t=this.items;this.items=[],this.record(()=>{this.items=t})}toArray(){return[...this.items]}sum(){let t=0;for(const e of this.items)t+=e;return t}avg(){return this.items.length>0?this.sum()/this.items.length:Number.NaN}min(){return this.items.reduce((t,e)=>e<t?e:t,this.items.length>0?1/0:Number.NaN)}max(){return this.items.reduce((t,e)=>e>t?e:t,this.items.length>0?-1/0:Number.NaN)}median(){const t=this.items.length;if(t===0)return Number.NaN;const e=[...this.items].sort((r,i)=>r-i),s=t>>1;return t%2===1?e[s]:(e[s-1]+e[s])/2}}function Ht(){return new Vt(I("state.array"))}const Xt=50,Gt=500,Z=n=>n===void 0||Number.isNaN(n)?Xt:Math.min(Gt,Math.max(1,Math.floor(n))),Yt=n=>!!n&&typeof n.bar=="number"&&typeof n.value=="number",Jt={label:["at"],line:["from","to"],box:["from","to"]};function ut(n){for(const t of Jt[n.kind])if(!Yt(n[t]))throw new Error(`a ${n.kind} needs ${t}: { bar, value }`);return n}const Qt=n=>({bar:n.bar,value:n.value});function at(n){const t={...n};for(const e of["at","from","to"]){const s=t[e];s&&(t[e]=Qt(s))}return t}class qt{constructor(t,e={}){this.scope=t,this.limits={label:Z(e.maxLabels),line:Z(e.maxLines),box:Z(e.maxBoxes)},t.units.push({commit:()=>{this.undo=[]},rollback:()=>{for(let s=this.undo.length-1;s>=0;s--)this.undo[s]();this.undo=[]}})}items=new Map;order={label:[],line:[],box:[]};limits;nextId=0;undo=[];label(t){return this.add({kind:"label",...t})}line(t){return this.add({kind:"line",...t})}box(t){return this.add({kind:"box",...t})}list(){return[...this.items.keys()].sort((t,e)=>t-e).map(t=>this.items.get(t))}record(t){this.scope.live&&this.undo.push(t)}add(t){ut(t);const e=this.nextId++;this.record(()=>{this.nextId=e}),this.items.set(e,at(t)),this.record(()=>{this.items.delete(e)});const s=this.order[t.kind];for(s.push(e),this.record(()=>{s.pop()});s.length>this.limits[t.kind];){const r=s.shift(),i=this.items.get(r);this.items.delete(r),this.record(()=>{this.items.set(r,i),s.unshift(r)})}return{set:r=>this.change(e,r),remove:()=>this.remove(e)}}change(t,e){const s=this.items.get(t);s&&(this.items.set(t,at(ut({...s,...e,kind:s.kind}))),this.record(()=>{this.items.set(t,s)}))}remove(t){const e=this.items.get(t);if(!e)return;this.items.delete(t);const s=this.order[e.kind],r=s.indexOf(t);r>=0&&s.splice(r,1),this.record(()=>{this.items.set(t,e),r>=0&&s.splice(r,0,t)})}}const te=1e11,V=(n,t)=>n?{open:n.open,high:Math.max(n.high,t.high),low:Math.min(n.low,t.low),close:t.close,volume:n.volume+t.volume}:{open:t.open,high:t.high,low:t.low,close:t.close,volume:t.volume},ee=(n,t)=>!!n&&n.open===t.open&&n.high===t.high&&n.low===t.low&&n.close===t.close&&n.volume===t.volume;function se(n){let t=1/0;for(let e=1;e<n.length;e++)t=Math.min(t,n[e].time-n[e-1].time);return!Number.isFinite(t)||t<=0?Number.NaN:n[n.length-1].time<te?t*1e3:t}function re(n,t,e,s={}){const r=typeof t=="string"?pt.timeframeToMs(t):Number.NaN;if(!Number.isFinite(r))throw new Error(`request.security: '${String(t)}' is no interval it can read: a count and a unit, as '15m', '1h', '4h', '1d', '1w', '1M' (case matters)`);const i=[];let o=!1;const u=new R(Nt({id:`security:${t}`,name:t,setup(d){const y=e({prices:d.prices,state:d.state});return k=>{i[k.index]=y(k.live===o?k:{...k,live:o})}}}),{},n.limits?{limits:{loopSteps:n.limits.loopSteps,arraySize:n.limits.arraySize}}:{});let c=null,a=-1,l=Number.NaN,m=Number.NaN,v=null,N=null,x=0;const S=(d,y,k)=>{const O={time:y,...d};u.length===0?u.load([O]):k&&u.length===x?u.next(O):u.tick(O);const w=u.errors[0];if(!w)return;const E=`request.security('${t}'), on its bar ${w.bar}: ${w.message}`;if(!w.limit)throw new Error(E);const T=new j(w.limit,E);throw n.onLimit?.(T),T},Wt=()=>{if(c)return c;const d=n.timeline(),y=se(d);if(Number.isFinite(y)&&r<y)throw new Error(`request.security('${t}') reads a higher interval than the chart's bars: they are ${y/6e4} minutes apart`);return c=B.periodKeyer(d,t,n.exchangeTimeZone,n.sessionStart),c};return d=>{const y=Wt();if(o=d.live,d.index===a){if(y(d.time)!==l)throw new Error(`request.security('${t}'): the live bar's time moved to another period; load the bars again`);const w=V(v,d);S(w,m,!1),N=w}else if(d.index===a+1){if(a>=0){const U=V(v,n.barAt(a));o=!1,ee(N,U)||S(U,m,!1),o=d.live,N=U}const w=y(d.time),E=w!==l||N===null,T=E?null:N,rt=V(T,d),nt=E?d.time:m;S(rt,nt,E),l=w,m=nt,v=T,N=rt,a=d.index,x=u.length}else throw new Error(`request.security('${t}') is called on every bar: it was not on bar ${a+1}`);const k=u.length-1,O=s.live?i[k]:i[k-1];return O===void 0?Number.NaN:O}}const ct=["time","open","high","low","close","volume"];class R{constructor(t,e={},s={}){this.script=t,this.params=e,this.options=s,this.limits=tt(s.limits),this.start()}scope;outputs;onBar;prices;count=0;failures=[];haltedAt=-1;declared;fresh=!1;get declarations(){return this.declared}loaded=[];limits;began=0;get errors(){return this.failures}get length(){return this.count}get output(){return this.outputs.output(this.count,this.failures)}load(t){this.loaded=t,this.fresh||this.start(),this.fresh=!1,this.clockIn();for(let e=0;e<t.length;e++)e===t.length-1&&this.goLive(),this.write(e,t[e]),this.count=e+1,this.runBar(e)}tick(t){if(this.count===0)return this.load([t]);this.fresh=!1,this.clockIn();const e=this.count-1;this.write(e,t);for(const s of this.scope.units)s.rollback();this.haltedAt===e&&(this.haltedAt=-1,this.failures=this.failures.filter(s=>s.bar!==e)),this.runBar(e)}next(t){if(this.count===0)return this.load([t]);this.fresh=!1,this.clockIn(),this.goLive();const e=this.count;this.write(e,t),this.count=e+1,this.runBar(e)}update(t){if(this.count===0)return this.load([t]),"bar";const e=this.prices.time.get(this.count-1);return t.time===e?(this.tick(t),"tick"):t.time>e?(this.next(t),"bar"):"reload"}start(){const t={units:[],live:!1,bar:0,clearers:[],limits:this.limits,steps:0,breach:null};this.scope=t,this.prices=Object.fromEntries(ct.map(r=>[r,q()])),this.outputs=new Dt(t),this.count=0,this.failures=[],this.haltedAt=-1;const e=this.script.inputs??{},s=Object.fromEntries(Object.keys(e).map(r=>[r,Kt(this.params[r],e[r])]));if(this.onBar=Pt(t,()=>this.script.setup({inputs:s,prices:this.priceSeries(),plot:(r,i)=>this.outputs.plot(r,i),loop:()=>{++t.steps>t.limits.loopSteps&&dt(t,"loop",`a bar takes at most ${t.limits.loopSteps} loop steps`)},shape:(r,i)=>this.outputs.shape(r,i),fill:(r,i,o)=>this.outputs.fill(r,i,o),bgcolor:r=>this.outputs.bgcolor(r),barcolor:()=>this.outputs.barcolor(),alertCondition:(r,i)=>this.outputs.alertCondition(r,i),drawings:r=>this.outputs.addDrawings(new qt(I("drawings"),r)),request:{security:(r,i,o)=>{const u=I("request.security"),c={timeline:()=>this.loaded,barAt:a=>this.barAt(a),...this.options,limits:this.limits,onLimit:a=>{u.breach??=a}};return re(c,r,i,o)}},hline:(r,i)=>this.outputs.hline(r,i),state:{var:Ut,array:Ht,series:Zt}})),this.outputs.close(),typeof this.onBar!="function")throw new Error(`script '${this.script.id}': setup must return what each bar runs`);this.declared=this.outputs.declarations(this.script.overlay===!0),this.fresh=!0}goLive(){for(const t of this.scope.units)t.commit();this.scope.live=!0}priceSeries(){const t=e=>({at:(s=0)=>s>=0?this.prices[e].get(this.scope.bar-Math.floor(s)):Number.NaN});return Object.fromEntries(ct.map(e=>[e,t(e)]))}write(t,e){const s=this.prices;s.time.set(t,e.time),s.open.set(t,e.open),s.high.set(t,e.high),s.low.set(t,e.low),s.close.set(t,e.close),s.volume.set(t,e.volume??0)}barAt(t){const e=this.prices;return{index:t,time:e.time.get(t),open:e.open.get(t),high:e.high.get(t),low:e.low.get(t),close:e.close.get(t),volume:e.volume.get(t),live:this.scope.live&&t===this.count-1}}runBar(t){const e=this.scope;e.bar=t;for(const o of e.clearers)o(t);if(this.haltedAt>=0)return;const s=this.barAt(t);e.steps=0,e.breach=null;let r=null;try{this.onBar(s)}catch(o){r=o}if(r=e.breach??r??this.overTime(),r===null)return;this.haltedAt=t;const i=r instanceof j?{limit:r.limit}:{};this.failures.push({bar:t,message:r instanceof Error?r.message:String(r),...i})}clockIn(){Number.isFinite(this.limits.runMs)&&(this.began=performance.now())}overTime(){const t=this.limits.runMs;return!Number.isFinite(t)||performance.now()-this.began<=t?null:new j("time",`a run takes at most ${t} ms; it was past that at this bar`)}}class p{constructor(t){this.size=t;const e=I();this.slots=new Float64Array(t+1).fill(Number.NaN),e.units.push({commit:()=>{this.kept={count:this.count,run:this.run},this.overwritten=[]},rollback:()=>{for(let s=this.overwritten.length-2;s>=0;s-=2)this.slots[this.overwritten[s]]=this.overwritten[s+1];this.overwritten=[],this.count=this.kept.count,this.run=this.kept.run}}),this.live=()=>e.live}slots;count=0;run=0;kept={count:0,run:0};overwritten=[];live;push(t){const e=this.count%this.slots.length;this.live()&&this.overwritten.push(e,this.slots[e]),this.slots[e]=t,this.count++,this.run=Number.isNaN(t)?0:this.run+1}at(t){const e=this.count-1-t;return t<0||t>this.size||e<0?Number.NaN:this.slots[e%this.slots.length]}get given(){return this.count}get numbersInRow(){return this.run}}function h(n){return Number.isFinite(n)?n:Number.NaN}function f(n){return Number.isFinite(n)?Math.max(1,Math.floor(n)):1}function L(n,t){const e=b({last:Number.NaN});return s=>{const r=h(s);return Number.isNaN(r)?(Number.isNaN(e.last)||n(e.last),t):(e.last=r,n(r))}}function et(){const n=b({close:Number.NaN});return t=>{const e=Number.isFinite(t.close)?t.close:n.close;n.close=e;const s=r=>Number.isFinite(r)?r:e;return{high:s(t.high),low:s(t.low),close:e}}}function bt(n){const t=f(n),e=new p(t),s=b({sum:0});return r=>{const i=h(r);return e.push(i),Number.isNaN(i)?(s.sum=0,Number.NaN):(s.sum+=i,e.numbersInRow>t&&(s.sum-=e.at(t)),e.numbersInRow>=t?s.sum/t:Number.NaN)}}function gt(n,t){const e=f(n),s=t(e),r=b({seed:0,count:0,value:Number.NaN});return i=>{const o=h(i);return Number.isNaN(o)?Number.NaN:Number.isNaN(r.value)?(r.seed+=o,r.count++,r.count===e&&(r.value=r.seed/e),r.value):(r.value+=s*(o-r.value),r.value)}}function K(n){return gt(n,t=>2/(t+1))}function ne(n){return gt(n,t=>1/t)}function g(n,t){if(n.given<t)return null;const e=new Array(t);for(let s=0;s<t;s++){const r=n.at(t-1-s);if(Number.isNaN(r))return null;e[s]=r}return e}function z(n){const t=f(n),e=new p(t),s=t*(t+1)/2;return r=>{e.push(h(r));const i=g(e,t);if(!i)return Number.NaN;let o=0;for(let u=0;u<t;u++)o+=i[u]*(u+1);return o/s}}function wt(n){const t=f(n),e=new p(t);return s=>{e.push(h(s));const r=g(e,t);if(!r)return Number.NaN;let i=0,o=0;for(const c of r)i+=c,o+=c*c;const u=i/t;return Math.sqrt(Math.max(0,o/t-u*u))}}function ie(n){return L(oe(n),Number.NaN)}function oe(n){const t=Math.max(2,f(n)),e=z(Math.max(2,Math.floor(t/2))),s=z(t),r=z(Math.max(2,Math.floor(Math.sqrt(t))));return i=>{const o=e(i),u=s(i);return r(Number.isNaN(o)||Number.isNaN(u)?Number.NaN:2*o-u)}}function ue(n){const t=f(n),e=new p(t),s=new p(t),r=b({pv:0,volume:0,last:Number.NaN});return(i,o)=>{const u=h(i);Number.isNaN(u)||(r.last=u);const c=r.last;if(Number.isNaN(c))return Number.NaN;const a=Number.isFinite(o)?o:0;return e.push(c),s.push(a),r.pv+=c*a,r.volume+=a,e.given>t&&(r.pv-=e.at(t)*s.at(t),r.volume-=s.at(t)),Number.isNaN(u)?Number.NaN:e.given>=t&&r.volume>0?r.pv/r.volume:Number.NaN}}function vt(n){const t=b({a:Number.NaN,b:Number.NaN});return(e,s)=>{const r=h(e),i=h(s),o=t.a,u=t.b;return t.a=r,t.b=i,[r,i,o,u].some(Number.isNaN)?!1:n?o<=u&&r>i:o>=u&&r<i}}function yt(){return vt(!0)}function kt(){return vt(!1)}function ae(){const n=yt(),t=kt();return(e,s)=>{const r=n(e,s),i=t(e,s);return r||i}}function Mt(n,t,e){const s=f(n),r=f(t),i=new p(s+r);return o=>{if(i.push(h(o)),i.given<s+r+1)return Number.NaN;const u=i.at(r);if(Number.isNaN(u))return Number.NaN;for(let c=0;c<=s+r;c++){if(c===r)continue;const a=i.at(c);if(Number.isNaN(a)||!e(u,a))return Number.NaN}return u}}function ce(n,t){return Mt(n,t,(e,s)=>e>s)}function le(n,t){return Mt(n,t,(e,s)=>e<s)}function he(){const n=b({since:Number.NaN});return t=>(n.since=t?0:n.since+1,n.since)}function me(n=0){const t=Math.max(0,Math.floor(n)),e=new p(t);return(s,r)=>(s&&e.push(h(r)),e.at(t))}function fe(n=14){return L(pe(n),Number.NaN)}function pe(n){const t=f(n),e=b({prev:Number.NaN,count:0,gain:0,loss:0}),s=()=>e.loss===0?100:100-100/(1+e.gain/e.loss);return r=>{const i=h(r);if(Number.isNaN(i))return Number.NaN;if(Number.isNaN(e.prev))return e.prev=i,Number.NaN;const o=i-e.prev;e.prev=i;const u=o>0?o:0,c=o<0?-o:0;return e.count<t?(e.gain+=u,e.loss+=c,e.count++,e.count<t?Number.NaN:(e.gain/=t,e.loss/=t,s())):(e.gain=(e.gain*(t-1)+u)/t,e.loss=(e.loss*(t-1)+c)/t,s())}}function Ne(n=12,t=26,e=9){return L(de(n,t,e),{macd:Number.NaN,signal:Number.NaN,histogram:Number.NaN})}function de(n,t,e){const s=K(n),r=K(t),i=K(e);return o=>{const u=s(o),c=r(o),a=Number.isNaN(u)||Number.isNaN(c)?Number.NaN:u-c,l=i(a);return{macd:a,signal:l,histogram:a-l}}}function be(n=20,t=2){return L(ge(n,t),{basis:Number.NaN,upper:Number.NaN,lower:Number.NaN})}function ge(n,t){const e=bt(n),s=wt(n);return r=>{const i=e(r),o=t*s(r);return{basis:i,upper:i+o,lower:i-o}}}function xt(n=1){const t=f(n),e=new p(t);return s=>(e.push(h(s)),e.at(0)-e.at(t))}function we(n=10){return L(xt(n),Number.NaN)}function ve(n=12){return L(ye(n),Number.NaN)}function ye(n){const t=f(n),e=new p(t);return s=>{e.push(h(s));const r=e.at(0),i=e.at(t);return Number.isNaN(r)||Number.isNaN(i)?Number.NaN:i===0?0:(r-i)/i*100}}function St(){const n=et(),t=b({prevClose:Number.NaN});return e=>{const s=n(e);if(Number.isNaN(s.close))return Number.NaN;const r=s.high-s.low,i=t.prevClose;return t.prevClose=s.close,Number.isNaN(i)?r:Math.max(r,Math.abs(s.high-i),Math.abs(s.low-i))}}function It(n=14){const t=f(n),e=St(),s=b({count:0,value:0});return r=>{const i=e(r);return Number.isNaN(i)?Number.NaN:s.count<t?(s.value+=i,s.count++,s.count<t?Number.NaN:(s.value/=t,s.value)):(s.value=(s.value*(t-1)+i)/t,s.value)}}function ke(n=3,t=10){const e=f(t),s=It(e),r=b({prevClose:Number.NaN,upper:0,lower:0,line:0}),i=et();return o=>{const u=s(o),c=i(o),a=Number.isNaN(r.prevClose)?c.close:r.prevClose;if(r.prevClose=c.close,Number.isNaN(u))return{value:Number.NaN,trend:Number.NaN};const l=(c.high+c.low)/2,m=l+n*u,v=l-n*u,N=m<r.upper||a>r.upper?m:r.upper,x=v>r.lower||a<r.lower?v:r.lower,S=r.line===r.upper?c.close<=N?N:x:c.close>=x?x:N;return r.upper=N,r.lower=x,r.line=S,{value:S,trend:S===x?1:-1}}}function Ot(n,t){const e=f(n),s=new p(e);return r=>{if(s.push(h(r)),s.given<e)return Number.NaN;let i=s.at(0);for(let o=0;o<e;o++){const u=s.at(o);if(Number.isNaN(u))return Number.NaN;t(u,i)&&(i=u)}return i}}function Me(n){return Ot(n,(t,e)=>t>e)}function xe(n){return Ot(n,(t,e)=>t<e)}function Se(n){const t=f(n),e=new p(t),s=new p(t);return(r,i,o)=>{e.push(h(i)),s.push(h(o));const u=g(e,t),c=g(s,t),a=h(r);if(!u||!c||Number.isNaN(a))return Number.NaN;const l=Math.max(...u),m=Math.min(...c);return l===m?50:(a-m)/(l-m)*100}}function Ie(n){const t=f(n),e=new p(t+1),s=new p(t+1);return(r,i)=>{e.push(h(r)),s.push(h(i));const o=g(e,t+1),u=g(s,t+1);if(!o||!u)return Number.NaN;let c=0,a=0;for(let l=1;l<=t;l++)o[l]>o[l-1]?c+=o[l]*u[l]:o[l]<o[l-1]&&(a+=o[l]*u[l]);return a===0?100:100-100/(1+c/a)}}function Oe(){const n=b({value:0,prev:Number.NaN});return(t,e)=>{const s=h(t);if(Number.isNaN(s))return Number.NaN;const r=n.prev;if(n.prev=s,Number.isNaN(r))return n.value;const i=Number.isFinite(e)?e:0;return s>r?n.value+=i:s<r&&(n.value-=i),n.value}}function Ee(n=.02,t=.02,e=.2){const s=et(),r=b({bars:0,up:0,af:0,ep:0,sar:0,high1:0,low1:0,high2:0,low2:0,close1:0});return i=>{const o=s(i);return Number.isNaN(o.close)?Number.NaN:(r.bars++,r.bars===1?(r.high1=o.high,r.low1=o.low,r.close1=o.close,Number.NaN):(r.bars===2&&(r.up=o.close>r.close1?1:0,r.af=n,r.ep=r.up?r.high1:r.low1,r.sar=r.up?r.low1:r.high1),r.sar+=r.af*(r.ep-r.sar),r.up?(r.sar=Math.min(r.sar,r.low1),r.bars>2&&(r.sar=Math.min(r.sar,r.low2)),o.low<r.sar?(r.up=0,r.sar=r.ep,r.ep=o.low,r.af=n):o.high>r.ep&&(r.ep=o.high,r.af=Math.min(r.af+t,e))):(r.sar=Math.max(r.sar,r.high1),r.bars>2&&(r.sar=Math.max(r.sar,r.high2)),o.high>r.sar?(r.up=1,r.sar=r.ep,r.ep=o.high,r.af=n):o.low<r.ep&&(r.ep=o.low,r.af=Math.min(r.af+t,e))),r.high2=r.high1,r.low2=r.low1,r.high1=o.high,r.low1=o.low,r.sar))}}function Et(n,t){const e=f(n),s=new p(e);return r=>{s.push(h(r));const i=g(s,e);if(!i)return Number.NaN;let o=e-1;for(let u=e-2;u>=0;u--)t(i[u],i[o])&&(o=u);return o-(e-1)}}function $e(n){return Et(n,(t,e)=>t>e)}function Ce(n){return Et(n,(t,e)=>t<e)}function $t(n,t){const e=f(n),s=new p(e+1);return r=>{s.push(h(r));const i=g(s,e+1);if(!i)return!1;for(let o=0;o<e;o++)if(!t(i[e],i[o]))return!1;return!0}}function Ae(n){return $t(n,(t,e)=>t>e)}function Le(n){return $t(n,(t,e)=>t<e)}function M(n,t){const e=f(n),s=new p(e);return r=>{s.push(h(r));const i=g(s,e);return i?t(i,e):Number.NaN}}const Ct=5e3,A=n=>n.reduce((t,e)=>t+e,0),st=n=>[...n].sort((t,e)=>t-e);function Te(n){return M(n,A)}function Fe(){const n=b({total:0,seen:0});return t=>{const e=h(t);return Number.isNaN(e)||(n.total+=e,n.seen=1),n.seen?n.total:Number.NaN}}function Be(n){return M(n,(t,e)=>{const s=st(t),r=Math.floor(e/2);return e%2===1?s[r]:(s[r-1]+s[r])/2})}function At(n){return Number.isFinite(n)?Math.min(100,Math.max(0,n)):Number.NaN}function je(n,t){const e=At(t);return M(n,(s,r)=>{if(Number.isNaN(e))return Number.NaN;const i=Math.max(1,Math.ceil(Math.round(e*r*1e6)/1e8));return st(s)[i-1]})}function Re(n,t){const e=At(t);return M(n,(s,r)=>{if(Number.isNaN(e))return Number.NaN;const i=st(s),o=e*(r-1)/100,u=Math.floor(o);return i[u]+(i[Math.ceil(o)]-i[u])*(o-u)})}function _e(n){const t=f(n),e=new p(t+1);return s=>{e.push(h(s));const r=g(e,t+1);if(!r)return Number.NaN;const i=r[t];let o=0;for(let u=0;u<t;u++)r[u]<=i&&o++;return o/t*100}}function We(n){return M(n,(t,e)=>{const s=A(t)/e;return A(t.map(r=>Math.abs(r-s)))/e})}function Ke(n){return M(n,(t,e)=>{let s=0,r=0;for(const o of t)s+=o,r+=o*o;const i=s/e;return Math.max(0,r/e-i*i)})}function ze(n){const t=f(n),e=new p(t),s=new p(t);return(r,i)=>{e.push(h(r)),s.push(h(i));const o=g(e,t),u=g(s,t);if(!o||!u)return Number.NaN;const c=A(o)/t,a=A(u)/t;let l=0,m=0,v=0;for(let N=0;N<t;N++)l+=(o[N]-c)*(u[N]-a),m+=(o[N]-c)**2,v+=(u[N]-a)**2;return m>0&&v>0?l/Math.sqrt(m*v):Number.NaN}}function De(n,t=0){const e=Math.max(-1e3,Math.round(Number.isFinite(t)?t:0));return M(Math.min(Ct,Math.max(2,f(n))),(s,r)=>{const i=r*(r-1)/2,o=(r-1)*r*(2*r-1)/6,u=r*o-i*i;let c=0,a=0;for(let m=0;m<r;m++)c+=s[m],a+=m*s[m];const l=(r*a-i*c)/u;return(c-l*i)/r+l*(r-1-e)})}function Pe(n,t=.85,e=6){const s=Math.min(Ct,f(n)),r=Math.min(1,Math.max(0,Number.isFinite(t)?t:.85))*(s-1),i=s/Math.max(.5,Number.isFinite(e)?e:6),o=Array.from({length:s},(c,a)=>Math.exp(-((a-r)**2)/(2*i*i))),u=A(o);return M(s,c=>{let a=0;for(let l=0;l<s;l++)a+=o[l]*c[l];return a/u})}function Ue(){return M(4,n=>(n[0]+2*n[1]+2*n[2]+n[3])/6)}const Ze={sma:bt,ema:K,rma:ne,wma:z,vwma:ue,hma:ie,stdev:wt,bb:be,rsi:fe,macd:Ne,change:xt,mom:we,roc:ve,tr:St,atr:It,supertrend:ke,highest:Me,lowest:xe,crossover:yt,crossunder:kt,cross:ae,pivothigh:ce,pivotlow:le,barssince:he,valuewhen:me,sum:Te,cum:Fe,median:Be,percentileNearestRank:je,percentileLinearInterpolation:Re,percentrank:_e,dev:We,variance:Ke,correlation:ze,linreg:De,alma:Pe,swma:Ue,stoch:Se,mfi:Ie,obv:Oe,sar:Ee,highestbars:$e,lowestbars:Ce,rising:Ae,falling:Le},H=1,$=n=>`p${n}`,Lt=n=>`s${n}`,D=n=>`bg${n}`,P=n=>`bc${n}`,C=n=>`${n}c`,Tt=n=>`f${n}c`,Ft=n=>`a${n}`;function W(n,t,e,s){const r=e[s];r>0&&(n[t]=r-1)}function Bt(n,t){const e={};n.plots.forEach((s,r)=>{const i=s.values[t];Number.isFinite(i)&&(e[$(r)]=i,W(e,C($(r)),s.colors,t))}),n.shapes.forEach((s,r)=>{s.on[t]===1&&(e[Lt(r)]=H)}),n.backgrounds.forEach((s,r)=>{s.colors[t]!==0&&(e[D(r)]=H,W(e,C(D(r)),s.colors,t))}),n.fills.forEach((s,r)=>W(e,Tt(r),s.colors,t)),n.barColors.forEach((s,r)=>{s[t]!==0&&(e[P(r)]=H,W(e,C(P(r)),s,t))}),n.alertConditions.forEach((s,r)=>{e[Ft(r)]=s.on[t]===1?1:0});for(const s in e)return e;return null}const lt=["#2962ff","#ff6d00","#00bfa5","#d500f9","#ffd600","#ef5350","#26a69a","#8d6e63"],Ve=.15;function He(n,t){return t||n==="top"||n==="bottom"?n:n==="aboveBar"?"top":"bottom"}function jt(n,t){return{...t?{limits:t}:{},...n.exchangeTimeZone?{exchangeTimeZone:n.exchangeTimeZone}:{},...n.sessionStart!==void 0?{sessionStart:n.sessionStart}:{}}}function J(n){return JSON.stringify(Object.keys(n).sort().map(t=>[t,n[t]]))}function Xe(n){const t=[];let e=0;const s=a=>(t.push(a??lt[e++%lt.length]),t.length-1),r=n.plots.map((a,l)=>({key:$(l),title:a.title,color:s(a.color),paletteBy:C($(l)),...a.kind!=="line"?{kind:a.kind}:{},...a.width!==void 0?{width:a.width}:{}})),i=n.shapes.map((a,l)=>({key:Lt(l),title:a.title,color:s(a.color),kind:"markers",shape:a.shape,position:He(a.position,n.overlay)})),o=n.backgrounds.map((a,l)=>({key:D(l),title:a.title,color:s(void 0),kind:"background",paletteBy:C(D(l)),opacity:1})),u=n.fills.map((a,l)=>{const m=t[r[a.between[0]].color];return{between:[$(a.between[0]),$(a.between[1])],color:s(a.color??pt.fadeBy(m,Ve)),paletteBy:Tt(l),opacity:1}}),c=Array.from({length:n.barColors},(a,l)=>({key:P(l),title:"Bars",color:s(void 0),kind:"barColor",paletteBy:C(P(l))}));return{plots:[...r,...i,...o,...c],fills:u,colors:t}}function Rt(n){const t=new R(n).declarations,{plots:e,fills:s,colors:r}=Xe(t),i=n.inputs??{},o=Object.keys(i);return{id:n.id,name:n.name,placement:t.overlay?"overlay":"panel",defaultConfig:Object.fromEntries(o.map(u=>[u,i[u].default])),plots:e,...s&&s.length>0?{fills:s}:{},...n.shortName!==void 0?{shortName:n.shortName}:{},...t.levels.length>0?{levels:t.levels.map(u=>u.price)}:{},...Ye(t.levels),...o.length>0?{inputs:Object.fromEntries(o.map(u=>{const{default:c,...a}=i[u];return[u,a]}))}:{},...r.length>0?{defaultStyle:{colors:r}}:{},...t.alertConditions.length>0?{alertConditions:t.alertConditions.map((u,c)=>({key:Ft(c),...u}))}:{},readsExchangeTimeZone:!0}}class Ge extends B.IndicatorBase{constructor(t,e={}){super(),this.script=t,this.options=e,this.descriptor=Rt(t)}descriptor;runs=new WeakMap;calculate(t,e){const s=new R(this.script,e.params,jt(e,this.options.limits));s.load(t);const r={values:new B.IndicatorValueMap,series:new Array(t.length).fill(null),meta:{}};return this.writeFrom(r,t,s,0),this.runs.set(r,{run:s,params:J(e.params)}),r}update(t,e,s,r){const i=this.runs.get(s);if(!i||i.params!==J(e.params)||!this.canResume(t,s,r))return null;const{run:o}=i;if(r<o.length-1||t.length<o.length)return null;for(let u=r;u<t.length;u++)u===o.length-1?o.tick(t[u]):o.next(t[u]);return s.series.length=t.length,this.writeFrom(s,t,o,r),s}writeFrom(t,e,s,r){const i=s.output;t.palette=i.palette,t.drawings=i.drawings,t.meta={...t.meta,errors:i.errors};for(let o=r;o<e.length;o++)this.writePoint(t,e,o,Bt(i,o))}}function Ye(n){const t=n.filter(e=>e.color!==void 0||e.lineStyle!==void 0||e.title!==void 0).map(({price:e,color:s,lineStyle:r,title:i})=>({price:e,...s!==void 0?{color:s}:{},...r!==void 0?{lineStyle:r}:{},...i!==void 0?{title:i}:{}}));return t.length>0?{levelLooks:t}:{}}function Je(n,t={}){return t.limits&&tt(t.limits),new Ge(n,t)}const Qe=5e3;function X(n){const t=n[n.length-1];return t?`${n.length}|${t.time}|${t.open}|${t.high}|${t.low}|${t.close}|${t.volume??0}`:"0"}function G(n){return`${J(n.params)}|${n.exchangeTimeZone??""}|${n.sessionStart??""}`}function qe(n){return{values:new B.IndicatorValueMap,series:new Array(n).fill(null),meta:{errors:[]}}}function ht(n,t){const e=n.series;for(e.length>t&&(e.length=t);e.length<t;)e.push(null);return n}class ts extends B.IndicatorBase{constructor(t,e){super(),this.script=t,this.options=e,this.descriptor=Rt(t),this.timeoutMs=e.timeoutMs??Qe}descriptor;worker=null;hosts=new Set;entries=new WeakMap;runs=new Map;pending=[];due=new Set;nextRun=1;nextSeq=1;timer=null;timeoutMs;connect(t){return this.hosts.add(t),()=>{this.hosts.delete(t)}}release(t){const e=this.entries.get(t);e&&(this.entries.delete(t),this.drop(e),this.runs.size===0&&this.stopWorker())}calculate(t,e){const s=this.entries.get(e);return s&&s.key===G(e)&&s.bars===t&&(s.stopped||s.sent!==""&&s.sent===X(t))?s.output:this.load(t,e,s).output}update(t,e,s,r){const i=this.entries.get(e);if(!i||i.output!==s||i.stopped||i.key!==G(e)||i.bars!==t||i.sent==="")return null;if(r<i.length-1||r>i.length||t.length<i.length)return i.sent="",null;for(let o=r;o<t.length;o++){const u=o===i.length-1?"tick":"next";this.send(i,{type:u,run:i.run,seq:this.nextSeq++,bar:t[o]}),u==="next"&&(i.length=o+1)}return ht(s,t.length),i.sent=X(t),s}load(t,e,s){s&&this.drop(s);const r={run:this.nextRun++,config:e,key:G(e),bars:t,output:s?ht(s.output,t.length):qe(t.length),length:t.length,sent:X(t),stopped:!1};return this.entries.set(e,r),this.runs.set(r.run,r),this.send(r,{type:"load",run:r.run,seq:this.nextSeq++,script:this.script.id,params:{...e.params},options:jt(e,this.options.limits),bars:t.map(i=>({...i}))}),r}drop(t){this.runs.delete(t.run)&&this.worker?.postMessage({type:"drop",run:t.run})}send(t,e){this.pending.push(t.run),this.ensureWorker().postMessage(e),this.pending.length===1&&this.armTimer()}ensureWorker(){if(this.worker)return this.worker;const t=this.options.spawn();return t.addEventListener("message",e=>{this.worker===t&&this.receive(e.data)}),this.worker=t,t}stopWorker(){this.timer&&clearTimeout(this.timer),this.timer=null,this.pending=[],this.worker?.terminate(),this.worker=null}armTimer(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.timedOut(),this.timeoutMs)}receive(t){this.pending.shift(),this.timer&&clearTimeout(this.timer),this.timer=null,this.pending.length>0&&this.armTimer();const e=this.runs.get(t.run);e&&(t.type==="patch"?this.apply(e,t.from,t.points,t.palette,t.drawings,t.errors):this.stop(e,{bar:Math.max(0,e.length-1),message:t.message}),this.recompute(e))}apply(t,e,s,r,i,o){const u=t.output,c=u.series;e===0&&(u.values.clear(),c.fill(null));for(let a=0;a<s.length;a++){const l=e+a;if(l>=t.bars.length)break;for(;c.length<=l;)c.push(null);this.writePoint(u,t.bars,l,s[a])}u.palette=r,u.drawings=i??[],u.meta={...u.meta,errors:o}}timedOut(){this.timer=null;const t=this.pending[0];this.stopWorker();const e=[...this.runs.values()];this.runs.clear();for(const s of e)s.run===t?this.stop(s,{bar:Math.max(0,s.length-1),message:`the script did not answer within ${this.timeoutMs} ms, and was stopped`,limit:"time"}):s.sent="",this.recompute(s)}stop(t,e){t.stopped=!0,this.runs.delete(t.run),t.output.meta={...t.output.meta,errors:[e]}}recompute(t){this.due.size===0&&queueMicrotask(()=>this.flush()),this.due.add(t)}flush(){const t=[...this.due];this.due.clear();for(const e of t)if(this.entries.get(e.config)===e)for(const s of this.hosts)s.recompute(e.config)}}function es(n,t){if(t.limits&&tt(t.limits),t.timeoutMs!==void 0&&!(t.timeoutMs>0))throw new RangeError(`scriptWorkerIndicator: timeoutMs must be a positive number, not ${t.timeoutMs}`);return new ts(n,t)}function mt(n){return n instanceof Error?n.message:String(n)}function ft(n,t,e,s){const r=e.output,i=[];for(let o=s;o<r.length;o++)i.push(Bt(r,o));return{type:"patch",run:n,seq:t,from:s,points:i,palette:[...r.palette],drawings:[...r.drawings],errors:[...r.errors]}}function _t(n,t){const e=new Map(n.map(i=>[i.id,i])),s=new Map,r=(i,o,u)=>t({type:"failed",run:i,seq:o,message:u});return i=>{if(i.type==="drop"){s.delete(i.run);return}if(i.type==="load"){s.delete(i.run);const c=e.get(i.script);if(!c)return r(i.run,i.seq,`no script '${i.script}' in this worker: give it to serveScripts`);try{const a=new R(c,i.params,i.options);a.load(i.bars),s.set(i.run,a),t(ft(i.run,i.seq,a,0))}catch(a){r(i.run,i.seq,mt(a))}return}const o=s.get(i.run);if(!o)return r(i.run,i.seq,`no run ${i.run} here: load it first`);const u=i.type==="tick"?o.length-1:o.length;try{i.type==="tick"?o.tick(i.bar):o.next(i.bar),t(ft(i.run,i.seq,o,Math.max(0,u)))}catch(c){s.delete(i.run),r(i.run,i.seq,mt(c))}}}function ss(n,t=self){const e=_t(n,s=>t.postMessage(s));t.addEventListener("message",s=>e(s.data))}exports.DEFAULT_LIMITS=Y;exports.ScriptLimitError=j;exports.ScriptRun=R;exports.createScriptHandler=_t;exports.defineScript=Nt;exports.scriptIndicator=Je;exports.scriptWorkerIndicator=es;exports.serveScripts=ss;exports.ta=Ze;
2
- //# sourceMappingURL=index.cjs.map
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`@tradecanvas/commons`),t=require(`@tradecanvas/core`);function n(e){if(typeof e.id!=`string`||e.id.trim()===``)throw Error(`defineScript: a script needs an id`);if(typeof e.setup!=`function`)throw Error(`defineScript('${e.id}'): a script needs a setup function`);return Object.freeze({...e,kind:`script`})}function r(e,t){let n=t.default;if(typeof n==`number`){let r=typeof e==`string`&&e.trim()!==``?Number(e):e;if(typeof r!=`number`||!Number.isFinite(r))return n;let i=t.kind===`int`?Math.floor(r):r;return Math.min(t.max??1/0,Math.max(t.min??-1/0,i))}return typeof e!=typeof n||t.options&&!t.options.some(t=>(typeof t==`object`?t.value:t)===e)?n:e}var i=256,a=class{data;filled=0;constructor(e,t){this.make=e,this.empty=t,this.data=e(i),this.data.fill(t)}set(e,t){this.reach(e+1),this.data[e]=t}get(e){return e>=0&&e<this.filled?this.data[e]:this.empty}reach(e){if(e>this.data.length){let t=this.data.length;for(;t<e;)t*=2;let n=this.make(t);n.fill(this.empty),n.set(this.data),this.data=n}e>this.filled&&(this.filled=e)}view(e){return this.reach(e),this.data.subarray(0,e)}},o=()=>new a(e=>new Float64Array(e),NaN),s=()=>new a(e=>new Uint16Array(e),0),c=()=>new a(e=>new Uint8Array(e),0),l=65535,u=class{plots=[];handles=new Map;shapes=[];fills=[];backgrounds=[];conditions=[];barColorSlots=[];levels=[];drawingLists=[];palette=[];paletteIndex=new Map;open=!0;constructor(e){this.scope=e,e.clearers.push(e=>{for(let t of this.plots)t.values.set(e,NaN),t.colors.set(e,0);for(let t of this.shapes)t.on.set(e,0);for(let t of this.fills)t.colors.set(e,0);for(let t of this.backgrounds)t.colors.set(e,0);for(let t of this.conditions)t.on.set(e,0);for(let t of this.barColorSlots)t.set(e,0)})}close(){this.open=!1}declaring(e){if(!this.open)throw Error(`${e} is declared in the script's setup, not on a bar`)}colorIndex(e){let t=this.paletteIndex.get(e);if(t===void 0){if(this.palette.length>=l)throw Error(`a script gives its bars at most ${l} colours`);this.palette.push(e),t=this.palette.length,this.paletteIndex.set(e,t)}return t}plot(e,t={}){this.declaring(`plot`);let n={declaration:{title:e,kind:t.kind??`line`,...t.color?{color:t.color}:{},...t.width?{width:t.width}:{}},values:o(),colors:s()};this.plots.push(n);let r={set:(e,t)=>(n.values.set(this.scope.bar,Number.isFinite(e)?e:NaN),t!==void 0&&n.colors.set(this.scope.bar,this.colorIndex(t)),e)};return this.handles.set(r,this.plots.length-1),r}shape(e,t={}){this.declaring(`shape`);let n={declaration:{title:e,shape:t.shape??`triangleUp`,position:t.position??`belowBar`,...t.color?{color:t.color}:{}},on:c()};return this.shapes.push(n),{set:e=>(n.on.set(this.scope.bar,+!!e),e)}}fill(e,t,n={}){this.declaring(`fill`);let r=this.handles.get(e),i=this.handles.get(t);if(r===void 0||i===void 0)throw Error(`fill is between two plots of the same script`);let a={declaration:{between:[r,i],...n.color?{color:n.color}:{}},colors:s()};return this.fills.push(a),{set:e=>{a.colors.set(this.scope.bar,e===void 0?0:this.colorIndex(e))}}}bgcolor(e={}){this.declaring(`bgcolor`);let t={declaration:{title:e.title??`Background`},colors:s()};return this.backgrounds.push(t),{set:e=>{t.colors.set(this.scope.bar,e===void 0?0:this.colorIndex(e))}}}addDrawings(e){return this.drawingLists.push(e),e}barcolor(){this.declaring(`barcolor`);let e=s();return this.barColorSlots.push(e),{set:t=>{e.set(this.scope.bar,t===void 0?0:this.colorIndex(t))}}}alertCondition(e,t={}){this.declaring(`alertCondition`);let n={declaration:{title:e,...t.message?{message:t.message}:{}},on:c()};return this.conditions.push(n),{set:e=>(n.on.set(this.scope.bar,+!!e),e)}}hline(e,t={}){this.declaring(`hline`),this.levels.push({price:e,...t})}declarations(e){return{overlay:e,plots:this.plots.map(e=>e.declaration),shapes:this.shapes.map(e=>e.declaration),levels:[...this.levels],fills:this.fills.map(e=>e.declaration),backgrounds:this.backgrounds.map(e=>e.declaration),barColors:this.barColorSlots.length,alertConditions:this.conditions.map(e=>e.declaration)}}output(e,t){return{length:e,plots:this.plots.map(t=>({...t.declaration,values:t.values.view(e),colors:t.colors.view(e)})),shapes:this.shapes.map(t=>({...t.declaration,on:t.on.view(e)})),levels:[...this.levels],fills:this.fills.map(t=>({...t.declaration,colors:t.colors.view(e)})),backgrounds:this.backgrounds.map(t=>({...t.declaration,colors:t.colors.view(e)})),barColors:this.barColorSlots.map(t=>t.view(e)),alertConditions:this.conditions.map(t=>({...t.declaration,on:t.on.view(e)})),palette:[...this.palette],drawings:this.drawingLists.flatMap(e=>e.list()),errors:[...t]}}},d=null;function f(e,t){let n=d;d=e;try{return t()}finally{d=n}}function p(e=`ta and state`){if(!d)throw Error(`${e} are made in a script's setup, not on a bar: each keeps the state of one script`);return d}function m(e){let t={...e},n={...e};return p().units.push({commit:()=>Object.assign(n,t),rollback:()=>Object.assign(t,n)}),t}var h={loopSteps:1e6,arraySize:1e5,runMs:1/0},g=class extends Error{constructor(e,t){super(t),this.limit=e,this.name=`ScriptLimitError`}};function _(e={}){let t=Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)),n={...h,...t};for(let e of Object.keys(h)){let t=n[e];if(typeof t!=`number`||Number.isNaN(t)||t<=0)throw RangeError(`script limits: ${e} must be a positive number, not ${String(t)}`)}return n}function v(e,t,n){let r=new g(t,n);throw e.breach??=r,r}function y(e){let t=p(`state.var`),n={value:e},r=e;return t.units.push({commit:()=>{r=n.value},rollback:()=>{n.value=r}}),n}function b(){let e=p(`state.series`),t=o();return e.clearers.push(e=>t.set(e,NaN)),{set:n=>(t.set(e.bar,n),n),at:(n=0)=>n>=0?t.get(e.bar-Math.floor(n)):NaN}}var ee=class{items=[];undo=[];constructor(e){this.scope=e,e.units.push({commit:()=>{this.undo=[]},rollback:()=>{for(let e=this.undo.length-1;e>=0;e--)this.undo[e]();this.undo=[]}})}record(e){this.scope.live&&this.undo.push(e)}grow(){let e=this.scope.limits.arraySize;this.items.length>=e&&v(this.scope,`array`,`a list holds at most ${e} numbers`)}size(){return this.items.length}get(e){let t=e<0?this.items.length+e:e;return t>=0&&t<this.items.length?this.items[t]:NaN}set(e,t){if(e<0||e>=this.items.length)throw RangeError(`array.set: index ${e} is outside a list of ${this.items.length}`);let n=this.items[e];this.items[e]=t,this.record(()=>{this.items[e]=n})}push(e){this.grow(),this.items.push(e),this.record(()=>{this.items.pop()})}pop(){if(this.items.length===0)return NaN;let e=this.items.pop();return this.record(()=>{this.items.push(e)}),e}shift(){if(this.items.length===0)return NaN;let e=this.items.shift();return this.record(()=>{this.items.unshift(e)}),e}unshift(e){this.grow(),this.items.unshift(e),this.record(()=>{this.items.shift()})}clear(){let e=this.items;this.items=[],this.record(()=>{this.items=e})}toArray(){return[...this.items]}sum(){let e=0;for(let t of this.items)e+=t;return e}avg(){return this.items.length>0?this.sum()/this.items.length:NaN}min(){return this.items.reduce((e,t)=>t<e?t:e,this.items.length>0?1/0:NaN)}max(){return this.items.reduce((e,t)=>t>e?t:e,this.items.length>0?-1/0:NaN)}median(){let e=this.items.length;if(e===0)return NaN;let t=[...this.items].sort((e,t)=>e-t),n=e>>1;return e%2==1?t[n]:(t[n-1]+t[n])/2}};function te(){return new ee(p(`state.array`))}var ne=50,re=500,x=e=>e===void 0||Number.isNaN(e)?ne:Math.min(re,Math.max(1,Math.floor(e))),ie=e=>!!e&&typeof e.bar==`number`&&typeof e.value==`number`,ae={label:[`at`],line:[`from`,`to`],box:[`from`,`to`]};function oe(e){for(let t of ae[e.kind])if(!ie(e[t]))throw Error(`a ${e.kind} needs ${t}: { bar, value }`);return e}var se=e=>({bar:e.bar,value:e.value});function S(e){let t={...e};for(let e of[`at`,`from`,`to`]){let n=t[e];n&&(t[e]=se(n))}return t}var ce=class{items=new Map;order={label:[],line:[],box:[]};limits;nextId=0;undo=[];constructor(e,t={}){this.scope=e,this.limits={label:x(t.maxLabels),line:x(t.maxLines),box:x(t.maxBoxes)},e.units.push({commit:()=>{this.undo=[]},rollback:()=>{for(let e=this.undo.length-1;e>=0;e--)this.undo[e]();this.undo=[]}})}label(e){return this.add({kind:`label`,...e})}line(e){return this.add({kind:`line`,...e})}box(e){return this.add({kind:`box`,...e})}list(){return[...this.items.keys()].sort((e,t)=>e-t).map(e=>this.items.get(e))}record(e){this.scope.live&&this.undo.push(e)}add(e){oe(e);let t=this.nextId++;this.record(()=>{this.nextId=t}),this.items.set(t,S(e)),this.record(()=>{this.items.delete(t)});let n=this.order[e.kind];for(n.push(t),this.record(()=>{n.pop()});n.length>this.limits[e.kind];){let e=n.shift(),t=this.items.get(e);this.items.delete(e),this.record(()=>{this.items.set(e,t),n.unshift(e)})}return{set:e=>this.change(t,e),remove:()=>this.remove(t)}}change(e,t){let n=this.items.get(e);n&&(this.items.set(e,S(oe({...n,...t,kind:n.kind}))),this.record(()=>{this.items.set(e,n)}))}remove(e){let t=this.items.get(e);if(!t)return;this.items.delete(e);let n=this.order[t.kind],r=n.indexOf(e);r>=0&&n.splice(r,1),this.record(()=>{this.items.set(e,t),r>=0&&n.splice(r,0,e)})}},le=1e11,C=(e,t)=>e?{open:e.open,high:Math.max(e.high,t.high),low:Math.min(e.low,t.low),close:t.close,volume:e.volume+t.volume}:{open:t.open,high:t.high,low:t.low,close:t.close,volume:t.volume},ue=(e,t)=>!!e&&e.open===t.open&&e.high===t.high&&e.low===t.low&&e.close===t.close&&e.volume===t.volume;function de(e){let t=1/0;for(let n=1;n<e.length;n++)t=Math.min(t,e[n].time-e[n-1].time);return!Number.isFinite(t)||t<=0?NaN:e[e.length-1].time<le?t*1e3:t}function fe(r,i,a,o={}){let s=typeof i==`string`?(0,e.timeframeToMs)(i):NaN;if(!Number.isFinite(s))throw Error(`request.security: '${String(i)}' is no interval it can read: a count and a unit, as '15m', '1h', '4h', '1d', '1w', '1M' (case matters)`);let c=[],l=!1,u=new T(n({id:`security:${i}`,name:i,setup(e){let t=a({prices:e.prices,state:e.state});return e=>{c[e.index]=t(e.live&&!l?{...e,live:!1}:e)}}}),{},r.limits?{limits:{loopSteps:r.limits.loopSteps,arraySize:r.limits.arraySize}}:{}),d=null,f=-1,p=NaN,m=NaN,h=null,_=null,v=0,y=(e,t,n)=>{let a={time:t,...e};u.length===0?u.load([a]):n&&u.length===v?u.next(a):u.tick(a);let o=u.errors[0];if(!o)return;let s=`request.security('${i}'), on its bar ${o.bar}: ${o.message}`;if(!o.limit)throw Error(s);let c=new g(o.limit,s);throw r.onLimit?.(c),c},b=()=>{if(d)return d;let e=r.timeline(),n=de(e);if(Number.isFinite(n)&&s<n)throw Error(`request.security('${i}') reads a higher interval than the chart's bars: they are ${n/6e4} minutes apart`);return d=(0,t.periodKeyer)(e,i,r.exchangeTimeZone,r.sessionStart),d};return e=>{let t=b();if(l=e.live,e.index===f){if(t(e.time)!==p)throw Error(`request.security('${i}'): the live bar's time moved to another period; load the bars again`);let n=C(h,e);y(n,m,!1),_=n}else if(e.index===f+1){if(f>=0){let t=C(h,r.barAt(f));l=!1,ue(_,t)||y(t,m,!1),l=e.live,_=t}let n=t(e.time),i=n!==p||_===null,a=i?null:_,o=C(a,e),s=i?e.time:m;y(o,s,i),p=n,m=s,h=a,_=o,f=e.index,v=u.length}else throw Error(`request.security('${i}') is called on every bar: it was not on bar ${f+1}`);let n=u.length-1,a=o.live?c[n]:c[n-1];return a===void 0?NaN:a}}var w=[`time`,`open`,`high`,`low`,`close`,`volume`],T=class{scope;outputs;onBar;prices;count=0;failures=[];haltedAt=-1;declared;fresh=!1;get declarations(){return this.declared}loaded=[];limits;began=0;intervalRead=!1;constructor(e,t={},n={}){this.script=e,this.params=t,this.options=n,this.limits=_(n.limits),this.start()}get errors(){return this.failures}get length(){return this.count}get output(){return this.outputs.output(this.count,this.failures)}load(e){this.loaded=e,this.fresh||this.start(),this.fresh=!1,this.clockIn();for(let t=0;t<e.length;t++)t===e.length-1&&this.goLive(),this.write(t,e[t]),this.count=t+1,this.runBar(t)}tick(e){if(this.count===0)return this.load([e]);this.fresh=!1,this.clockIn();let t=this.count-1;this.write(t,e);for(let e of this.scope.units)e.rollback();this.haltedAt===t&&(this.haltedAt=-1,this.failures=this.failures.filter(e=>e.bar!==t)),this.runBar(t)}next(e){if(this.count===0)return this.load([e]);this.fresh=!1,this.clockIn(),this.closeLive(),this.goLive();let t=this.count;this.write(t,e),this.count=t+1,this.runBar(t)}update(e){if(this.count===0)return this.load([e]),`bar`;let t=this.prices.time.get(this.count-1);return e.time===t?(this.tick(e),`tick`):e.time>t?(this.next(e),`bar`):`reload`}start(){let e={units:[],live:!1,bar:0,clearers:[],limits:this.limits,steps:0,breach:null};this.scope=e,this.prices=Object.fromEntries(w.map(e=>[e,o()])),this.outputs=new u(e),this.count=0,this.failures=[],this.haltedAt=-1;let t=this.script.inputs??{},n=Object.fromEntries(Object.keys(t).map(e=>[e,r(this.params[e],t[e])]));if(this.onBar=f(e,()=>this.script.setup({inputs:n,chart:this.chart(),prices:this.priceSeries(),plot:(e,t)=>this.outputs.plot(e,t),loop:()=>{++e.steps>e.limits.loopSteps&&v(e,`loop`,`a bar takes at most ${e.limits.loopSteps} loop steps`)},shape:(e,t)=>this.outputs.shape(e,t),fill:(e,t,n)=>this.outputs.fill(e,t,n),bgcolor:e=>this.outputs.bgcolor(e),barcolor:()=>this.outputs.barcolor(),alertCondition:(e,t)=>this.outputs.alertCondition(e,t),drawings:e=>this.outputs.addDrawings(new ce(p(`drawings`),e)),request:{security:(e,t,n)=>{let r=p(`request.security`);return fe({timeline:()=>this.loaded,barAt:e=>this.barAt(e),...this.options,limits:this.limits,onLimit:e=>{r.breach??=e}},e,t,n)}},hline:(e,t)=>this.outputs.hline(e,t),state:{var:y,array:te,series:b}})),this.outputs.close(),typeof this.onBar!=`function`)throw Error(`script '${this.script.id}': setup must return what each bar runs`);this.declared=this.outputs.declarations(this.script.overlay===!0),this.fresh=!0}chart(){let{exchangeTimeZone:e=`UTC`,interval:t=null}=this.options,n=()=>(this.intervalRead=!0,t);return Object.freeze({timeZone:e,get interval(){return n()}})}get readsInterval(){return this.intervalRead}goLive(){for(let e of this.scope.units)e.commit();this.scope.live=!0}closeLive(){if(!(this.haltedAt>=0)){for(let e of this.scope.units)e.rollback();this.scope.live=!1,this.runBar(this.count-1)}}priceSeries(){let e=e=>({at:(t=0)=>t>=0?this.prices[e].get(this.scope.bar-Math.floor(t)):NaN});return Object.fromEntries(w.map(t=>[t,e(t)]))}write(e,t){let n=this.prices;n.time.set(e,t.time),n.open.set(e,t.open),n.high.set(e,t.high),n.low.set(e,t.low),n.close.set(e,t.close),n.volume.set(e,t.volume??0)}barAt(e){let t=this.prices;return{index:e,time:t.time.get(e),open:t.open.get(e),high:t.high.get(e),low:t.low.get(e),close:t.close.get(e),volume:t.volume.get(e),live:this.scope.live&&e===this.count-1}}runBar(e){let t=this.scope;t.bar=e;for(let n of t.clearers)n(e);if(this.haltedAt>=0)return;let n=this.barAt(e);t.steps=0,t.breach=null;let r=null;try{this.onBar(n)}catch(e){r=e}if(r=t.breach??r??this.overTime(),r===null)return;this.haltedAt=e;let i=r instanceof g?{limit:r.limit}:{};this.failures.push({bar:e,message:r instanceof Error?r.message:String(r),...i})}clockIn(){Number.isFinite(this.limits.runMs)&&(this.began=performance.now())}overTime(){let e=this.limits.runMs;return!Number.isFinite(e)||performance.now()-this.began<=e?null:new g(`time`,`a run takes at most ${e} ms; it was past that at this bar`)}},E=class{slots;count=0;run=0;kept={count:0,run:0};overwritten=[];constructor(e){this.size=e;let t=p();this.slots=new Float64Array(e+1).fill(NaN),t.units.push({commit:()=>{this.kept={count:this.count,run:this.run},this.overwritten=[]},rollback:()=>{for(let e=this.overwritten.length-2;e>=0;e-=2)this.slots[this.overwritten[e]]=this.overwritten[e+1];this.overwritten=[],this.count=this.kept.count,this.run=this.kept.run}}),this.live=()=>t.live}live;push(e){let t=this.count%this.slots.length;this.live()&&this.overwritten.push(t,this.slots[t]),this.slots[t]=e,this.count++,this.run=Number.isNaN(e)?0:this.run+1}at(e){let t=this.count-1-e;return e<0||e>this.size||t<0?NaN:this.slots[t%this.slots.length]}get given(){return this.count}get numbersInRow(){return this.run}};function D(e){return Number.isFinite(e)?e:NaN}function O(e){return Number.isFinite(e)?Math.max(1,Math.floor(e)):1}function k(e,t){let n=m({last:NaN});return r=>{let i=D(r);return Number.isNaN(i)?(Number.isNaN(n.last)||e(n.last),t):(n.last=i,e(i))}}function A(){let e=m({close:NaN});return t=>{let n=Number.isFinite(t.close)?t.close:e.close;e.close=n;let r=e=>Number.isFinite(e)?e:n;return{high:r(t.high),low:r(t.low),close:n}}}function j(e){let t=O(e),n=new E(t),r=m({sum:0});return e=>{let i=D(e);return n.push(i),Number.isNaN(i)?(r.sum=0,NaN):(r.sum+=i,n.numbersInRow>t&&(r.sum-=n.at(t)),n.numbersInRow>=t?r.sum/t:NaN)}}function M(e,t){let n=O(e),r=t(n),i=m({seed:0,count:0,value:NaN});return e=>{let t=D(e);return Number.isNaN(t)?NaN:Number.isNaN(i.value)?(i.seed+=t,i.count++,i.count===n&&(i.value=i.seed/n),i.value):(i.value+=r*(t-i.value),i.value)}}function N(e){return M(e,e=>2/(e+1))}function pe(e){return M(e,e=>1/e)}function P(e,t){if(e.given<t)return null;let n=Array(t);for(let r=0;r<t;r++){let i=e.at(t-1-r);if(Number.isNaN(i))return null;n[r]=i}return n}function F(e){let t=O(e),n=new E(t),r=t*(t+1)/2;return e=>{n.push(D(e));let i=P(n,t);if(!i)return NaN;let a=0;for(let e=0;e<t;e++)a+=i[e]*(e+1);return a/r}}function me(e){let t=O(e),n=new E(t);return e=>{n.push(D(e));let r=P(n,t);if(!r)return NaN;let i=0,a=0;for(let e of r)i+=e,a+=e*e;let o=i/t;return Math.sqrt(Math.max(0,a/t-o*o))}}function he(e){return k(ge(e),NaN)}function ge(e){let t=Math.max(2,O(e)),n=F(Math.max(2,Math.floor(t/2))),r=F(t),i=F(Math.max(2,Math.floor(Math.sqrt(t))));return e=>{let t=n(e),a=r(e);return i(Number.isNaN(t)||Number.isNaN(a)?NaN:2*t-a)}}function _e(e){let t=O(e),n=new E(t),r=new E(t),i=m({pv:0,volume:0,last:NaN});return(e,a)=>{let o=D(e);Number.isNaN(o)||(i.last=o);let s=i.last;if(Number.isNaN(s))return NaN;let c=Number.isFinite(a)?a:0;return n.push(s),r.push(c),i.pv+=s*c,i.volume+=c,n.given>t&&(i.pv-=n.at(t)*r.at(t),i.volume-=r.at(t)),Number.isNaN(o)?NaN:n.given>=t&&i.volume>0?i.pv/i.volume:NaN}}function ve(e){let t=m({a:NaN,b:NaN});return(n,r)=>{let i=D(n),a=D(r),o=t.a,s=t.b;return t.a=i,t.b=a,[i,a,o,s].some(Number.isNaN)?!1:e?o<=s&&i>a:o>=s&&i<a}}function ye(){return ve(!0)}function be(){return ve(!1)}function xe(){let e=ye(),t=be();return(n,r)=>{let i=e(n,r),a=t(n,r);return i||a}}function Se(e,t,n){let r=O(e),i=O(t),a=new E(r+i);return e=>{if(a.push(D(e)),a.given<r+i+1)return NaN;let t=a.at(i);if(Number.isNaN(t))return NaN;for(let e=0;e<=r+i;e++){if(e===i)continue;let r=a.at(e);if(Number.isNaN(r)||!n(t,r))return NaN}return t}}function Ce(e,t){return Se(e,t,(e,t)=>e>t)}function we(e,t){return Se(e,t,(e,t)=>e<t)}function Te(){let e=m({since:NaN});return t=>(e.since=t?0:e.since+1,e.since)}function Ee(e=0){let t=Math.max(0,Math.floor(e)),n=new E(t);return(e,r)=>(e&&n.push(D(r)),n.at(t))}function De(e=14){return k(Oe(e),NaN)}function Oe(e){let t=O(e),n=m({prev:NaN,count:0,gain:0,loss:0}),r=()=>n.loss===0?100:100-100/(1+n.gain/n.loss);return e=>{let i=D(e);if(Number.isNaN(i))return NaN;if(Number.isNaN(n.prev))return n.prev=i,NaN;let a=i-n.prev;n.prev=i;let o=a>0?a:0,s=a<0?-a:0;return n.count<t?(n.gain+=o,n.loss+=s,n.count++,n.count<t?NaN:(n.gain/=t,n.loss/=t,r())):(n.gain=(n.gain*(t-1)+o)/t,n.loss=(n.loss*(t-1)+s)/t,r())}}function ke(e=12,t=26,n=9){return k(Ae(e,t,n),{macd:NaN,signal:NaN,histogram:NaN})}function Ae(e,t,n){let r=N(e),i=N(t),a=N(n);return e=>{let t=r(e),n=i(e),o=Number.isNaN(t)||Number.isNaN(n)?NaN:t-n,s=a(o);return{macd:o,signal:s,histogram:o-s}}}function je(e=20,t=2){return k(Me(e,t),{basis:NaN,upper:NaN,lower:NaN})}function Me(e,t){let n=j(e),r=me(e);return e=>{let i=n(e),a=t*r(e);return{basis:i,upper:i+a,lower:i-a}}}function Ne(e=1){let t=O(e),n=new E(t);return e=>(n.push(D(e)),n.at(0)-n.at(t))}function Pe(e=10){return k(Ne(e),NaN)}function Fe(e=12){return k(Ie(e),NaN)}function Ie(e){let t=O(e),n=new E(t);return e=>{n.push(D(e));let r=n.at(0),i=n.at(t);return Number.isNaN(r)||Number.isNaN(i)?NaN:i===0?0:(r-i)/i*100}}function Le(){let e=A(),t=m({prevClose:NaN});return n=>{let r=e(n);if(Number.isNaN(r.close))return NaN;let i=r.high-r.low,a=t.prevClose;return t.prevClose=r.close,Number.isNaN(a)?i:Math.max(i,Math.abs(r.high-a),Math.abs(r.low-a))}}function I(e=14){let t=O(e),n=Le(),r=m({count:0,value:0});return e=>{let i=n(e);return Number.isNaN(i)?NaN:r.count<t?(r.value+=i,r.count++,r.count<t?NaN:(r.value/=t,r.value)):(r.value=(r.value*(t-1)+i)/t,r.value)}}function Re(e=3,t=10){let n=I(O(t)),r=m({prevClose:NaN,upper:0,lower:0,line:0}),i=A();return t=>{let a=n(t),o=i(t),s=Number.isNaN(r.prevClose)?o.close:r.prevClose;if(r.prevClose=o.close,Number.isNaN(a))return{value:NaN,trend:NaN};let c=(o.high+o.low)/2,l=c+e*a,u=c-e*a,d=l<r.upper||s>r.upper?l:r.upper,f=u>r.lower||s<r.lower?u:r.lower,p=r.line===r.upper?o.close<=d?d:f:o.close>=f?f:d;return r.upper=d,r.lower=f,r.line=p,{value:p,trend:p===f?1:-1}}}function L(e,t){let n=O(e),r=new E(n);return e=>{if(r.push(D(e)),r.given<n)return NaN;let i=r.at(0);for(let e=0;e<n;e++){let n=r.at(e);if(Number.isNaN(n))return NaN;t(n,i)&&(i=n)}return i}}function ze(e){return L(e,(e,t)=>e>t)}function Be(e){return L(e,(e,t)=>e<t)}function Ve(e){let t=O(e),n=new E(t),r=new E(t);return(e,i,a)=>{n.push(D(i)),r.push(D(a));let o=P(n,t),s=P(r,t),c=D(e);if(!o||!s||Number.isNaN(c))return NaN;let l=Math.max(...o),u=Math.min(...s);return l===u?50:(c-u)/(l-u)*100}}function He(e){let t=O(e),n=new E(t+1),r=new E(t+1);return(e,i)=>{n.push(D(e)),r.push(D(i));let a=P(n,t+1),o=P(r,t+1);if(!a||!o)return NaN;let s=0,c=0;for(let e=1;e<=t;e++)a[e]>a[e-1]?s+=a[e]*o[e]:a[e]<a[e-1]&&(c+=a[e]*o[e]);return c===0?100:100-100/(1+s/c)}}function Ue(){let e=m({value:0,prev:NaN});return(t,n)=>{let r=D(t);if(Number.isNaN(r))return NaN;let i=e.prev;if(e.prev=r,Number.isNaN(i))return e.value;let a=Number.isFinite(n)?n:0;return r>i?e.value+=a:r<i&&(e.value-=a),e.value}}function We(e=.02,t=.02,n=.2){let r=A(),i=m({bars:0,up:0,af:0,ep:0,sar:0,high1:0,low1:0,high2:0,low2:0,close1:0});return a=>{let o=r(a);return Number.isNaN(o.close)?NaN:(i.bars++,i.bars===1?(i.high1=o.high,i.low1=o.low,i.close1=o.close,NaN):(i.bars===2&&(i.up=+(o.close>i.close1),i.af=e,i.ep=i.up?i.high1:i.low1,i.sar=i.up?i.low1:i.high1),i.sar+=i.af*(i.ep-i.sar),i.up?(i.sar=Math.min(i.sar,i.low1),i.bars>2&&(i.sar=Math.min(i.sar,i.low2)),o.low<i.sar?(i.up=0,i.sar=i.ep,i.ep=o.low,i.af=e):o.high>i.ep&&(i.ep=o.high,i.af=Math.min(i.af+t,n))):(i.sar=Math.max(i.sar,i.high1),i.bars>2&&(i.sar=Math.max(i.sar,i.high2)),o.high>i.sar?(i.up=1,i.sar=i.ep,i.ep=o.high,i.af=e):o.low<i.ep&&(i.ep=o.low,i.af=Math.min(i.af+t,n))),i.high2=i.high1,i.low2=i.low1,i.high1=o.high,i.low1=o.low,i.sar))}}function R(e,t){let n=O(e),r=new E(n);return e=>{r.push(D(e));let i=P(r,n);if(!i)return NaN;let a=n-1;for(let e=n-2;e>=0;e--)t(i[e],i[a])&&(a=e);return a-(n-1)}}function Ge(e){return R(e,(e,t)=>e>t)}function Ke(e){return R(e,(e,t)=>e<t)}function z(e,t){let n=O(e),r=new E(n+1);return e=>{r.push(D(e));let i=P(r,n+1);if(!i)return!1;for(let e=0;e<n;e++)if(!t(i[n],i[e]))return!1;return!0}}function qe(e){return z(e,(e,t)=>e>t)}function Je(e){return z(e,(e,t)=>e<t)}function B(e,t){let n=O(e),r=new E(n);return e=>{r.push(D(e));let i=P(r,n);return i?t(i,n):NaN}}var V=5e3,H=e=>e.reduce((e,t)=>e+t,0),U=e=>[...e].sort((e,t)=>e-t);function Ye(e){return B(e,H)}function Xe(){let e=m({total:0,seen:0});return t=>{let n=D(t);return Number.isNaN(n)||(e.total+=n,e.seen=1),e.seen?e.total:NaN}}function Ze(e){return B(e,(e,t)=>{let n=U(e),r=Math.floor(t/2);return t%2==1?n[r]:(n[r-1]+n[r])/2})}function W(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):NaN}function Qe(e,t){let n=W(t);return B(e,(e,t)=>{if(Number.isNaN(n))return NaN;let r=Math.max(1,Math.ceil(Math.round(n*t*1e6)/1e8));return U(e)[r-1]})}function $e(e,t){let n=W(t);return B(e,(e,t)=>{if(Number.isNaN(n))return NaN;let r=U(e),i=n*(t-1)/100,a=Math.floor(i);return r[a]+(r[Math.ceil(i)]-r[a])*(i-a)})}function et(e){let t=O(e),n=new E(t+1);return e=>{n.push(D(e));let r=P(n,t+1);if(!r)return NaN;let i=r[t],a=0;for(let e=0;e<t;e++)r[e]<=i&&a++;return a/t*100}}function tt(e){return B(e,(e,t)=>{let n=H(e)/t;return H(e.map(e=>Math.abs(e-n)))/t})}function nt(e){return B(e,(e,t)=>{let n=0,r=0;for(let t of e)n+=t,r+=t*t;let i=n/t;return Math.max(0,r/t-i*i)})}function rt(e){let t=O(e),n=new E(t),r=new E(t);return(e,i)=>{n.push(D(e)),r.push(D(i));let a=P(n,t),o=P(r,t);if(!a||!o)return NaN;let s=H(a)/t,c=H(o)/t,l=0,u=0,d=0;for(let e=0;e<t;e++)l+=(a[e]-s)*(o[e]-c),u+=(a[e]-s)**2,d+=(o[e]-c)**2;return u>0&&d>0?l/Math.sqrt(u*d):NaN}}function it(e,t=0){let n=Math.max(-1e3,Math.round(Number.isFinite(t)?t:0));return B(Math.min(V,Math.max(2,O(e))),(e,t)=>{let r=t*(t-1)/2,i=t*((t-1)*t*(2*t-1)/6)-r*r,a=0,o=0;for(let n=0;n<t;n++)a+=e[n],o+=n*e[n];let s=(t*o-r*a)/i;return(a-s*r)/t+s*(t-1-n)})}function at(e,t=.85,n=6){let r=Math.min(V,O(e)),i=Math.min(1,Math.max(0,Number.isFinite(t)?t:.85))*(r-1),a=r/Math.max(.5,Number.isFinite(n)?n:6),o=Array.from({length:r},(e,t)=>Math.exp(-((t-i)**2)/(2*a*a))),s=H(o);return B(r,e=>{let t=0;for(let n=0;n<r;n++)t+=o[n]*e[n];return t/s})}function ot(){return B(4,e=>(e[0]+2*e[1]+2*e[2]+e[3])/6)}var st={sma:j,ema:N,rma:pe,wma:F,vwma:_e,hma:he,stdev:me,bb:je,rsi:De,macd:ke,change:Ne,mom:Pe,roc:Fe,tr:Le,atr:I,supertrend:Re,highest:ze,lowest:Be,crossover:ye,crossunder:be,cross:xe,pivothigh:Ce,pivotlow:we,barssince:Te,valuewhen:Ee,sum:Ye,cum:Xe,median:Ze,percentileNearestRank:Qe,percentileLinearInterpolation:$e,percentrank:et,dev:tt,variance:nt,correlation:rt,linreg:it,alma:at,swma:ot,stoch:Ve,mfi:He,obv:Ue,sar:We,highestbars:Ge,lowestbars:Ke,rising:qe,falling:Je},G=1,K=e=>`p${e}`,ct=e=>`s${e}`,q=e=>`bg${e}`,J=e=>`bc${e}`,Y=e=>`${e}c`,lt=e=>`f${e}c`,ut=e=>`a${e}`;function X(e,t,n,r){let i=n[r];i>0&&(e[t]=i-1)}function dt(e,t){let n={};e.plots.forEach((e,r)=>{let i=e.values[t];Number.isFinite(i)&&(n[K(r)]=i,X(n,Y(K(r)),e.colors,t))}),e.shapes.forEach((e,r)=>{e.on[t]===1&&(n[ct(r)]=G)}),e.backgrounds.forEach((e,r)=>{e.colors[t]!==0&&(n[q(r)]=G,X(n,Y(q(r)),e.colors,t))}),e.fills.forEach((e,r)=>X(n,lt(r),e.colors,t)),e.barColors.forEach((e,r)=>{e[t]!==0&&(n[J(r)]=G,X(n,Y(J(r)),e,t))}),e.alertConditions.forEach((e,r)=>{n[ut(r)]=+(e.on[t]===1)});for(let e in n)return n;return null}var ft=[`#2962ff`,`#ff6d00`,`#00bfa5`,`#d500f9`,`#ffd600`,`#ef5350`,`#26a69a`,`#8d6e63`],pt=.15;function mt(e,t){return t||e===`top`||e===`bottom`?e:e===`aboveBar`?`top`:`bottom`}function ht(e,t){return{...t?{limits:t}:{},...e.exchangeTimeZone?{exchangeTimeZone:e.exchangeTimeZone}:{},...e.sessionStart===void 0?{}:{sessionStart:e.sessionStart},...e.interval===void 0?{}:{interval:e.interval}}}function Z(e){return JSON.stringify(Object.keys(e).sort().map(t=>[t,e[t]]))}function gt(t){let n=[],r=0,i=e=>(n.push(e??ft[r++%ft.length]),n.length-1),a=t.plots.map((e,t)=>({key:K(t),title:e.title,color:i(e.color),paletteBy:Y(K(t)),...e.kind===`line`?{}:{kind:e.kind},...e.width===void 0?{}:{width:e.width}})),o=t.shapes.map((e,n)=>({key:ct(n),title:e.title,color:i(e.color),kind:`markers`,shape:e.shape,position:mt(e.position,t.overlay)})),s=t.backgrounds.map((e,t)=>({key:q(t),title:e.title,color:i(void 0),kind:`background`,paletteBy:Y(q(t)),opacity:1})),c=t.fills.map((t,r)=>{let o=n[a[t.between[0]].color];return{between:[K(t.between[0]),K(t.between[1])],color:i(t.color??(0,e.fadeBy)(o,pt)),paletteBy:lt(r),opacity:1}}),l=Array.from({length:t.barColors},(e,t)=>({key:J(t),title:`Bars`,color:i(void 0),kind:`barColor`,paletteBy:Y(J(t))}));return{plots:[...a,...o,...s,...l],fills:c,colors:n}}function _t(e){let t=new T(e),n=t.declarations,{plots:r,fills:i,colors:a}=gt(n),o=e.inputs??{},s=Object.keys(o);return{id:e.id,name:e.name,placement:n.overlay?`overlay`:`panel`,defaultConfig:Object.fromEntries(s.map(e=>[e,o[e].default])),plots:r,...i&&i.length>0?{fills:i}:{},...e.shortName===void 0?{}:{shortName:e.shortName},...n.levels.length>0?{levels:n.levels.map(e=>e.price)}:{},...yt(n.levels),...s.length>0?{inputs:Object.fromEntries(s.map(e=>{let{default:t,...n}=o[e];return[e,n]}))}:{},...a.length>0?{defaultStyle:{colors:a}}:{},...n.alertConditions.length>0?{alertConditions:n.alertConditions.map((e,t)=>({key:ut(t),...e}))}:{},readsExchangeTimeZone:!0,...t.readsInterval?{readsInterval:!0}:{}}}var vt=class extends t.IndicatorBase{descriptor;runs=new WeakMap;constructor(e,t={}){super(),this.script=e,this.options=t,this.descriptor=_t(e)}calculate(e,n){let r=new T(this.script,n.params,ht(n,this.options.limits));r.load(e);let i={values:new t.IndicatorValueMap,series:Array(e.length).fill(null),meta:{}};return this.writeFrom(i,e,r,0),this.runs.set(i,{run:r,params:Z(n.params),interval:n.interval}),i}update(e,t,n,r){let i=this.runs.get(n),a=this.descriptor.readsInterval===!0&&i?.interval!==t.interval;if(!i||a||i.params!==Z(t.params)||!this.canResume(e,n,r))return null;let{run:o}=i;if(r<o.length-1||e.length<o.length)return null;for(let t=r;t<e.length;t++)t===o.length-1?o.tick(e[t]):o.next(e[t]);return n.series.length=e.length,this.writeFrom(n,e,o,Math.max(0,r-1)),n}revisesBefore(){return 1}writeFrom(e,t,n,r){let i=n.output;e.palette=i.palette,e.drawings=i.drawings,e.meta={...e.meta,errors:i.errors};for(let n=r;n<t.length;n++)this.writePoint(e,t,n,dt(i,n))}};function yt(e){let t=e.filter(e=>e.color!==void 0||e.lineStyle!==void 0||e.title!==void 0).map(({price:e,color:t,lineStyle:n,title:r})=>({price:e,...t===void 0?{}:{color:t},...n===void 0?{}:{lineStyle:n},...r===void 0?{}:{title:r}}));return t.length>0?{levelLooks:t}:{}}function bt(e,t={}){return t.limits&&_(t.limits),new vt(e,t)}var xt=5e3;function Q(e){let t=e[e.length-1];return t?`${e.length}|${t.time}|${t.open}|${t.high}|${t.low}|${t.close}|${t.volume??0}`:`0`}function St(e,t){return`${Z(e.params)}|${e.exchangeTimeZone??``}|${e.sessionStart??``}|${t?e.interval??``:``}`}function Ct(e){return{values:new t.IndicatorValueMap,series:Array(e).fill(null),meta:{errors:[]}}}function wt(e,t){let n=e.series;for(n.length>t&&(n.length=t);n.length<t;)n.push(null);return e}var Tt=class extends t.IndicatorBase{descriptor;worker=null;hosts=new Set;entries=new WeakMap;runs=new Map;pending=[];due=new Set;nextRun=1;nextSeq=1;timer=null;timeoutMs;constructor(e,t){super(),this.script=e,this.options=t,this.descriptor=_t(e),this.timeoutMs=t.timeoutMs??xt}connect(e){return this.hosts.add(e),()=>{this.hosts.delete(e)}}release(e){let t=this.entries.get(e);t&&(this.entries.delete(e),this.drop(t),this.runs.size===0&&this.stopWorker())}calculate(e,t){let n=this.entries.get(t);return n&&n.key===this.keyOf(t)&&n.bars===e&&(n.stopped||n.sent!==``&&n.sent===Q(e))?n.output:this.load(e,t,n).output}update(e,t,n,r){let i=this.entries.get(t);if(!i||i.output!==n||i.stopped||i.key!==this.keyOf(t)||i.bars!==e||i.sent===``)return null;if(r<i.length-1||r>i.length||e.length<i.length)return i.sent=``,null;for(let t=r;t<e.length;t++){let n=t===i.length-1?`tick`:`next`;this.send(i,{type:n,run:i.run,seq:this.nextSeq++,bar:e[t]}),n===`next`&&(i.length=t+1)}return wt(n,e.length),i.sent=Q(e),n}keyOf(e){return St(e,this.descriptor.readsInterval===!0)}load(e,t,n){n&&this.drop(n);let r={run:this.nextRun++,config:t,key:this.keyOf(t),bars:e,output:n?wt(n.output,e.length):Ct(e.length),length:e.length,sent:Q(e),stopped:!1};return this.entries.set(t,r),this.runs.set(r.run,r),this.send(r,{type:`load`,run:r.run,seq:this.nextSeq++,script:this.script.id,params:{...t.params},options:ht(t,this.options.limits),bars:e.map(e=>({...e}))}),r}drop(e){this.runs.delete(e.run)&&this.worker?.postMessage({type:`drop`,run:e.run})}send(e,t){this.pending.push(e.run),this.ensureWorker().postMessage(t),this.pending.length===1&&this.armTimer()}ensureWorker(){if(this.worker)return this.worker;let e=this.options.spawn();return e.addEventListener(`message`,t=>{this.worker===e&&this.receive(t.data)}),this.worker=e,e}stopWorker(){this.timer&&clearTimeout(this.timer),this.timer=null,this.pending=[],this.worker?.terminate(),this.worker=null}armTimer(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.timedOut(),this.timeoutMs)}receive(e){this.pending.shift(),this.timer&&clearTimeout(this.timer),this.timer=null,this.pending.length>0&&this.armTimer();let t=this.runs.get(e.run);t&&(e.type===`patch`?this.apply(t,e.from,e.points,e.palette,e.drawings,e.errors):this.stop(t,{bar:Math.max(0,t.length-1),message:e.message}),this.recompute(t))}apply(e,t,n,r,i,a){let o=e.output,s=o.series;t===0&&(o.values.clear(),s.fill(null));for(let r=0;r<n.length;r++){let i=t+r;if(i>=e.bars.length)break;for(;s.length<=i;)s.push(null);this.writePoint(o,e.bars,i,n[r])}o.palette=r,o.drawings=i??[],o.meta={...o.meta,errors:a}}timedOut(){this.timer=null;let e=this.pending[0];this.stopWorker();let t=[...this.runs.values()];this.runs.clear();for(let n of t)n.run===e?this.stop(n,{bar:Math.max(0,n.length-1),message:`the script did not answer within ${this.timeoutMs} ms, and was stopped`,limit:`time`}):n.sent=``,this.recompute(n)}stop(e,t){e.stopped=!0,this.runs.delete(e.run),e.output.meta={...e.output.meta,errors:[t]}}recompute(e){this.due.size===0&&queueMicrotask(()=>this.flush()),this.due.add(e)}flush(){let e=[...this.due];this.due.clear();for(let t of e)if(this.entries.get(t.config)===t)for(let e of this.hosts)e.recompute(t.config)}};function Et(e,t){if(t.limits&&_(t.limits),t.timeoutMs!==void 0&&!(t.timeoutMs>0))throw RangeError(`scriptWorkerIndicator: timeoutMs must be a positive number, not ${t.timeoutMs}`);return new Tt(e,t)}function Dt(e){return e instanceof Error?e.message:String(e)}function $(e,t,n,r){let i=n.output,a=[];for(let e=r;e<i.length;e++)a.push(dt(i,e));return{type:`patch`,run:e,seq:t,from:r,points:a,palette:[...i.palette],drawings:[...i.drawings],errors:[...i.errors]}}function Ot(e,t){let n=new Map(e.map(e=>[e.id,e])),r=new Map,i=(e,n,r)=>t({type:`failed`,run:e,seq:n,message:r});return e=>{if(e.type===`drop`){r.delete(e.run);return}if(e.type===`load`){r.delete(e.run);let a=n.get(e.script);if(!a)return i(e.run,e.seq,`no script '${e.script}' in this worker: give it to serveScripts`);try{let n=new T(a,e.params,e.options);n.load(e.bars),r.set(e.run,n),t($(e.run,e.seq,n,0))}catch(t){i(e.run,e.seq,Dt(t))}return}let a=r.get(e.run);if(!a)return i(e.run,e.seq,`no run ${e.run} here: load it first`);let o=a.length-1;try{e.type===`tick`?a.tick(e.bar):a.next(e.bar),t($(e.run,e.seq,a,Math.max(0,o)))}catch(t){r.delete(e.run),i(e.run,e.seq,Dt(t))}}}function kt(e,t=self){let n=Ot(e,e=>t.postMessage(e));t.addEventListener(`message`,e=>n(e.data))}exports.DEFAULT_LIMITS=h,exports.ScriptLimitError=g,exports.ScriptRun=T,exports.createScriptHandler=Ot,exports.defineScript=n,exports.scriptIndicator=bt,exports.scriptWorkerIndicator=Et,exports.serveScripts=kt,exports.ta=st;
2
+ //# sourceMappingURL=index.cjs.map