@tradecanvas/script 0.0.0-stage → 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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +125 -2
  3. package/dist/Column.d.ts +21 -0
  4. package/dist/Column.d.ts.map +1 -0
  5. package/dist/Ring.d.ts +28 -0
  6. package/dist/Ring.d.ts.map +1 -0
  7. package/dist/ScriptRun.d.ts +85 -0
  8. package/dist/ScriptRun.d.ts.map +1 -0
  9. package/dist/defineScript.d.ts +216 -0
  10. package/dist/defineScript.d.ts.map +1 -0
  11. package/dist/drawings.d.ts +46 -0
  12. package/dist/drawings.d.ts.map +1 -0
  13. package/dist/index.cjs +2 -0
  14. package/dist/index.cjs.map +1 -0
  15. package/dist/index.d.ts +20 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +1726 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/limits.d.ts +30 -0
  20. package/dist/limits.d.ts.map +1 -0
  21. package/dist/outputs.d.ts +129 -0
  22. package/dist/outputs.d.ts.map +1 -0
  23. package/dist/points.d.ts +13 -0
  24. package/dist/points.d.ts.map +1 -0
  25. package/dist/scope.d.ts +33 -0
  26. package/dist/scope.d.ts.map +1 -0
  27. package/dist/scriptIndicator.d.ts +25 -0
  28. package/dist/scriptIndicator.d.ts.map +1 -0
  29. package/dist/security.d.ts +52 -0
  30. package/dist/security.d.ts.map +1 -0
  31. package/dist/state.d.ts +52 -0
  32. package/dist/state.d.ts.map +1 -0
  33. package/dist/ta/averages.d.ts +19 -0
  34. package/dist/ta/averages.d.ts.map +1 -0
  35. package/dist/ta/common.d.ts +24 -0
  36. package/dist/ta/common.d.ts.map +1 -0
  37. package/dist/ta/events.d.ts +16 -0
  38. package/dist/ta/events.d.ts.map +1 -0
  39. package/dist/ta/index.d.ts +65 -0
  40. package/dist/ta/index.d.ts.map +1 -0
  41. package/dist/ta/moves.d.ts +26 -0
  42. package/dist/ta/moves.d.ts.map +1 -0
  43. package/dist/ta/oscillators.d.ts +29 -0
  44. package/dist/ta/oscillators.d.ts.map +1 -0
  45. package/dist/ta/ranges.d.ts +18 -0
  46. package/dist/ta/ranges.d.ts.map +1 -0
  47. package/dist/ta/statistics.d.ts +26 -0
  48. package/dist/ta/statistics.d.ts.map +1 -0
  49. package/dist/worker/messages.d.ts +49 -0
  50. package/dist/worker/messages.d.ts.map +1 -0
  51. package/dist/worker/scriptWorkerIndicator.d.ts +40 -0
  52. package/dist/worker/scriptWorkerIndicator.d.ts.map +1 -0
  53. package/dist/worker/serveScripts.d.ts +28 -0
  54. package/dist/worker/serveScripts.d.ts.map +1 -0
  55. package/package.json +39 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/defineScript.ts","../src/Column.ts","../src/outputs.ts","../src/scope.ts","../src/limits.ts","../src/state.ts","../src/drawings.ts","../src/security.ts","../src/ScriptRun.ts","../src/Ring.ts","../src/ta/common.ts","../src/ta/averages.ts","../src/ta/events.ts","../src/ta/oscillators.ts","../src/ta/ranges.ts","../src/ta/moves.ts","../src/ta/statistics.ts","../src/ta/index.ts","../src/points.ts","../src/scriptIndicator.ts","../src/worker/scriptWorkerIndicator.ts","../src/worker/serveScripts.ts"],"sourcesContent":["import type { IndicatorInputSpec, IndicatorMarkerShape } from '@tradecanvas/commons';\nimport type { ScriptArray, ScriptSeries, Var } from './state.js';\nimport type { DrawingLimits, ScriptDrawings } from './drawings.js';\nimport type { SecurityOptions, SecuritySetup } from './security.js';\nimport type { LineStyle, TimeFrame } from '@tradecanvas/commons';\n\nexport type ScriptInputValue = number | string | boolean;\n\n/** An input of a script: its default, and how the settings dialog shows it. */\nexport interface ScriptInput extends IndicatorInputSpec {\n default: ScriptInputValue;\n}\n\nexport type ScriptInputs = Record<string, ScriptInput>;\n\n/** The values of a script's inputs, by name. */\nexport type InputValues<I extends ScriptInputs> = {\n readonly [K in keyof I]: I[K]['default'] extends number ? number : I[K]['default'] extends boolean ? boolean : string;\n};\n\n/** The bar being run. */\nexport interface ScriptBar {\n /** Its place among the bars, from 0. */\n readonly index: number;\n /** Its time, ms since the epoch. */\n readonly time: number;\n readonly open: number;\n readonly high: number;\n readonly low: number;\n readonly close: number;\n readonly volume: number;\n /**\n * The live bar: the last, run again on each tick until the next bar\n * comes. False on the bars that closed, the live one too when the next\n * bar comes: it is run once more as it closes.\n */\n readonly live: boolean;\n}\n\n/** A price of the bars, read back from the bar being run. */\nexport interface PriceSeries {\n /** Its value `back` bars ago (0: this bar's); NaN before the first bar. */\n at(back?: number): number;\n}\n\nexport interface ScriptPrices {\n readonly time: PriceSeries;\n readonly open: PriceSeries;\n readonly high: PriceSeries;\n readonly low: PriceSeries;\n readonly close: PriceSeries;\n readonly volume: PriceSeries;\n}\n\n/** How a plot is drawn: `'area'` a line with the space down to zero shaded under it. */\nexport type ScriptPlotKind = 'line' | 'histogram' | 'dots' | 'step' | 'area';\n\nexport interface PlotOptions {\n /** Its colour (`'#rrggbb'`, `'#rrggbbaa'`); unset: the theme's next series colour. */\n color?: string;\n kind?: ScriptPlotKind;\n /** Its line width in px. */\n width?: number;\n}\n\nexport interface PlotHandle {\n /** This bar's value, and a colour for this bar only; returns the value. */\n set(value: number, color?: string): number;\n}\n\n/**\n * Where a mark goes: over or under its bar, or at the top or the bottom of\n * the pane. In a pane of its own, over the bar is the top and under it the\n * bottom.\n */\nexport type ShapePosition = 'aboveBar' | 'belowBar' | 'top' | 'bottom';\n\nexport interface ShapeOptions {\n shape?: IndicatorMarkerShape;\n /** Default under the bar. */\n position?: ShapePosition;\n color?: string;\n}\n\nexport interface ShapeHandle {\n /** Whether this bar is marked; returns it. */\n set(on: boolean): boolean;\n}\n\nexport interface FillOptions {\n /** Its colour, for the bars given none; a colour with an alpha of its own (`'#3b82f633'`) is shaded at that alpha. Unset: the first plot's, faint. */\n color?: string;\n}\n\nexport interface FillHandle {\n /** This bar's colour (from the bar before to this one); unset: the fill's own. */\n set(color?: string): void;\n}\n\nexport interface BackgroundOptions {\n /** Its name, for the settings. */\n title?: string;\n}\n\nexport interface BackgroundHandle {\n /** The colour behind this bar, the pane's whole height; unset: none. */\n set(color?: string): void;\n}\n\nexport interface AlertConditionOptions {\n /** What the alert says when it fires, unless the viewer writes their own. */\n message?: string;\n}\n\nexport interface AlertConditionHandle {\n /** Whether the condition holds on this bar; returns it. */\n set(on: boolean): boolean;\n}\n\nexport interface BarColorHandle {\n /** The colour of this bar's candle (or OHLC bar); unset: the chart's own. */\n set(color?: string): void;\n}\n\nexport interface HlineOptions {\n /** Drawn whole in it; unset: faint, in the axis colour. */\n color?: string;\n /** Default `'dashed'`. Without a colour, in the axis colour, faint. */\n lineStyle?: LineStyle;\n /** Its name: not drawn, and not shown in the indicator settings yet. */\n title?: string;\n}\n\n/** The chart a script runs on. */\nexport interface ScriptChart {\n /** The exchange's IANA zone (`'Asia/Ho_Chi_Minh'`); `'UTC'` when the chart names none. */\n readonly timeZone: string;\n /**\n * The chart's interval (`'5m'`, `'1d'`), null when it is not known. Read\n * it in setup: the script is then run again when it changes. What a\n * script declares (its plots, inputs, levels) may not depend on it.\n */\n readonly interval: TimeFrame | null;\n}\n\n/** What a script's setup is given to declare what it draws and keeps. */\nexport interface ScriptSetup<V> {\n readonly inputs: V;\n readonly chart: ScriptChart;\n /** The bars' prices, read back from the bar being run (`prices.close.at(1)`). */\n readonly prices: ScriptPrices;\n /** A value a bar drawn as a line, histogram, dots or steps. */\n plot(title: string, options?: PlotOptions): PlotHandle;\n /** A mark over or under the bars it is set on, or at the top or the bottom of the pane. */\n shape(title: string, options?: ShapeOptions): ShapeHandle;\n /** The area between two plots, in a colour a bar if need be. */\n fill(a: PlotHandle, b: PlotHandle, options?: FillOptions): FillHandle;\n /** A colour behind the bars it is set on, the pane's whole height. */\n bgcolor(options?: BackgroundOptions): BackgroundHandle;\n /**\n * The price bars painted in a colour a bar, for a script drawn over the\n * prices (`overlay: true`), on a chart of candles or OHLC bars (another\n * chart type, Renko or a line, shows them as they are).\n */\n barcolor(): BarColorHandle;\n /**\n * A moment the script says, which a viewer can set an alert on: the\n * widget's alert form lists it as \"<name>: <title>\", and the alert fires\n * as it turns true. `.set(true)` on the bars it holds.\n */\n alertCondition(title: string, options?: AlertConditionOptions): AlertConditionHandle;\n /**\n * Labels, lines and boxes the script draws on its bars (`label()`,\n * `line()`, `box()`), each a handle to change or take away later; past\n * the limit of a kind, the oldest goes. Keep a handle across bars in\n * `state.var`: a plain variable is not put back on a tick, and may then\n * reach a shape made since in its place.\n */\n drawings(limits?: DrawingLimits): ScriptDrawings;\n /** Data the chart's bars do not hold as they are. */\n readonly request: {\n /**\n * A value of a higher interval of the same symbol (`'1h'` on a 5-minute\n * chart), a chart bar at a time: `setup` makes the sums of that\n * interval's bars and returns their value a bar. Each chart bar reads\n * the value of the last bar of the higher interval that closed before\n * its own; with `{ live: true }`, the forming one's as it was then (it\n * repaints). Neither reads a bar after the chart's own. Made in setup,\n * called on every bar.\n */\n security(interval: TimeFrame, setup: SecuritySetup, options?: SecurityOptions): (bar: ScriptBar) => number;\n };\n /** A level drawn across the pane. */\n hline(price: number, options?: HlineOptions): void;\n /**\n * Count one step of a loop, on a bar: call it once each time round. Past\n * the run's `loopSteps` (a million unless set) the script stops at that\n * bar, so a loop that never ends is stopped.\n */\n loop(): void;\n readonly state: {\n /** A value kept from bar to bar: a number, a text, or a handle (a drawing's), put back as it was on a tick. */\n var<T>(init: T): Var<T>;\n /** A list of numbers kept from bar to bar. */\n array(): ScriptArray;\n /** A value a bar of the script's own, read back with `at(n)`. */\n series(): ScriptSeries;\n };\n}\n\n/** What a script's setup returns: what to do on each bar. */\nexport type OnBar = (bar: ScriptBar) => void;\n\nexport interface ScriptDefinition<I extends ScriptInputs> {\n /** Its id as an indicator: unique among the chart's indicators. */\n id: string;\n name: string;\n /** Its name in the legend; unset: its name. */\n shortName?: string;\n /** Drawn over the prices; unset: in a pane of its own. */\n overlay?: boolean;\n inputs?: I;\n /**\n * Run once, before the first bar: declares the plots, makes the `ta`\n * sums and the kept state, and returns what each bar runs.\n */\n setup(api: ScriptSetup<InputValues<I>>): OnBar;\n}\n\n/** A script, ready to run (`new ScriptRun`) or to draw (`scriptIndicator`). */\nexport interface Script<I extends ScriptInputs = ScriptInputs> extends Readonly<ScriptDefinition<I>> {\n readonly kind: 'script';\n}\n\n/** A script written bar by bar. */\nexport function defineScript<I extends ScriptInputs = Record<string, never>>(definition: ScriptDefinition<I>): Script<I> {\n if (typeof definition.id !== 'string' || definition.id.trim() === '') throw new Error('defineScript: a script needs an id');\n if (typeof definition.setup !== 'function') throw new Error(`defineScript('${definition.id}'): a script needs a setup function`);\n return Object.freeze({ ...definition, kind: 'script' as const });\n}\n\n/**\n * An input's value as a bar sees it: what was set when it is of the\n * default's type, else the default; a number within `min` and `max`, whole\n * for an `'int'`; a choice one of the `options`. The rules\n * `defineIndicator` reads its inputs by.\n */\nexport function inputValue(set: unknown, input: ScriptInput): ScriptInputValue {\n const fallback = input.default;\n if (typeof fallback === 'number') {\n const typed = typeof set === 'string' && set.trim() !== '' ? Number(set) : set;\n if (typeof typed !== 'number' || !Number.isFinite(typed)) return fallback;\n const value = input.kind === 'int' ? Math.floor(typed) : typed;\n return Math.min(input.max ?? Infinity, Math.max(input.min ?? -Infinity, value));\n }\n if (typeof set !== typeof fallback) return fallback;\n if (input.options && !input.options.some((option) => (typeof option === 'object' ? option.value : option) === set)) return fallback;\n return set as ScriptInputValue;\n}\n","type TypedArray = Float64Array | Uint16Array | Uint8Array;\n\nconst FIRST_CAPACITY = 256;\n\n/** A value a bar that grows with the bars, in a typed array. */\nexport class Column<T extends TypedArray> {\n private data: T;\n private filled = 0;\n\n constructor(\n private readonly make: (capacity: number) => T,\n private readonly empty: number,\n ) {\n this.data = make(FIRST_CAPACITY);\n this.data.fill(empty);\n }\n\n /** Set bar `index`, growing to it. */\n set(index: number, value: number): void {\n this.reach(index + 1);\n this.data[index] = value;\n }\n\n get(index: number): number {\n return index >= 0 && index < this.filled ? this.data[index] : this.empty;\n }\n\n /** Make room for `length` bars, the new ones empty. */\n reach(length: number): void {\n if (length > this.data.length) {\n let capacity = this.data.length;\n while (capacity < length) capacity *= 2;\n const next = this.make(capacity);\n next.fill(this.empty);\n next.set(this.data);\n this.data = next;\n }\n if (length > this.filled) this.filled = length;\n }\n\n /** Its first `length` bars, without copying them: good until a bar is set past what it holds. */\n view(length: number): T {\n this.reach(length);\n return this.data.subarray(0, length) as T;\n }\n}\n\nexport const floatColumn = (): Column<Float64Array> => new Column((n) => new Float64Array(n), Number.NaN);\nexport const colorColumn = (): Column<Uint16Array> => new Column((n) => new Uint16Array(n), 0);\nexport const flagColumn = (): Column<Uint8Array> => new Column((n) => new Uint8Array(n), 0);\n","import type { IndicatorDrawing, IndicatorMarkerShape, LineStyle } from '@tradecanvas/commons';\nimport type { ScriptDrawings } from './drawings.js';\nimport type { ScriptLimit } from './limits.js';\nimport { colorColumn, flagColumn, floatColumn, type Column } from './Column.js';\nimport type {\n BarColorHandle,\n AlertConditionHandle,\n AlertConditionOptions,\n BackgroundHandle,\n BackgroundOptions,\n FillHandle,\n FillOptions,\n HlineOptions,\n PlotHandle,\n PlotOptions,\n ScriptPlotKind,\n ShapeHandle,\n ShapeOptions,\n ShapePosition,\n} from './defineScript.js';\nimport type { Scope } from './scope.js';\n\nexport interface PlotDeclaration {\n readonly title: string;\n readonly kind: ScriptPlotKind;\n readonly color?: string;\n readonly width?: number;\n}\n\nexport interface ShapeDeclaration {\n readonly title: string;\n readonly shape: IndicatorMarkerShape;\n readonly position: ShapePosition;\n readonly color?: string;\n}\n\nexport interface LevelDeclaration {\n readonly price: number;\n readonly color?: string;\n readonly lineStyle?: LineStyle;\n readonly title?: string;\n}\n\nexport interface FillDeclaration {\n /** The two plots it shades between, by their place among the plots. */\n readonly between: readonly [number, number];\n readonly color?: string;\n}\n\nexport interface BackgroundDeclaration {\n readonly title: string;\n}\n\nexport interface AlertConditionDeclaration {\n readonly title: string;\n readonly message?: string;\n}\n\n/** What a script draws, known once its setup has run. */\nexport interface ScriptDeclarations {\n readonly overlay: boolean;\n readonly plots: readonly PlotDeclaration[];\n readonly shapes: readonly ShapeDeclaration[];\n readonly levels: readonly LevelDeclaration[];\n readonly fills: readonly FillDeclaration[];\n readonly backgrounds: readonly BackgroundDeclaration[];\n /** How many `barcolor()` the script asked for. */\n readonly barColors: number;\n readonly alertConditions: readonly AlertConditionDeclaration[];\n}\n\n/** A colour a bar, by its place in the output's `palette` plus one: 0 for none. */\nexport type BarColors = Uint16Array;\n\n/** A plot's values, a bar each, and the colour each bar was given. */\nexport interface PlotOutput extends PlotDeclaration {\n readonly values: Float64Array;\n /** Each bar's colour: 0 for the plot's own. */\n readonly colors: BarColors;\n}\n\nexport interface ShapeOutput extends ShapeDeclaration {\n /** 1 on the bars it marks. */\n readonly on: Uint8Array;\n}\n\nexport interface FillOutput extends FillDeclaration {\n /** Each bar's colour: 0 for the fill's own. */\n readonly colors: BarColors;\n}\n\nexport interface BackgroundOutput extends BackgroundDeclaration {\n /** Each bar's colour: 0 for no background there. */\n readonly colors: BarColors;\n}\n\nexport interface AlertConditionOutput extends AlertConditionDeclaration {\n /** 1 on the bars it holds. */\n readonly on: Uint8Array;\n}\n\nexport interface ScriptError {\n /** The bar it stopped at. */\n readonly bar: number;\n readonly message: string;\n /** The limit it went past, when that is why it stopped. */\n readonly limit?: ScriptLimit;\n}\n\n/** What a run has drawn so far, a value a bar, without copying. */\nexport interface ScriptOutput {\n readonly length: number;\n readonly plots: readonly PlotOutput[];\n readonly shapes: readonly ShapeOutput[];\n readonly levels: readonly LevelDeclaration[];\n readonly fills: readonly FillOutput[];\n readonly backgrounds: readonly BackgroundOutput[];\n /** Each `barcolor()`'s colour a bar: 0 for the chart's own. */\n readonly barColors: readonly BarColors[];\n readonly alertConditions: readonly AlertConditionOutput[];\n /** The colours bars were given, each once. */\n readonly palette: readonly string[];\n /** The labels, lines and boxes it keeps, in the order made. */\n readonly drawings: readonly IndicatorDrawing[];\n readonly errors: readonly ScriptError[];\n}\n\n/** The most colours a script's bars take: each bar keeps its colour's place in 16 bits, 0 for none. */\nconst MAX_COLORS = 65535;\n\ninterface PlotSlot {\n declaration: PlotDeclaration;\n values: Column<Float64Array>;\n colors: Column<Uint16Array>;\n}\n\ninterface ShapeSlot {\n declaration: ShapeDeclaration;\n on: Column<Uint8Array>;\n}\n\ninterface ColorSlot<D> {\n declaration: D;\n colors: Column<Uint16Array>;\n}\n\n/** The plots, marks, fills, backgrounds and levels a script declares, and what its bars set in them. */\nexport class Outputs {\n private readonly plots: PlotSlot[] = [];\n private readonly handles = new Map<PlotHandle, number>();\n private readonly shapes: ShapeSlot[] = [];\n private readonly fills: ColorSlot<FillDeclaration>[] = [];\n private readonly backgrounds: ColorSlot<BackgroundDeclaration>[] = [];\n private readonly conditions: { declaration: AlertConditionDeclaration; on: Column<Uint8Array> }[] = [];\n private readonly barColorSlots: Column<Uint16Array>[] = [];\n private readonly levels: LevelDeclaration[] = [];\n private readonly drawingLists: ScriptDrawings[] = [];\n private readonly palette: string[] = [];\n private readonly paletteIndex = new Map<string, number>();\n private open = true;\n\n constructor(private readonly scope: Scope) {\n scope.clearers.push((bar) => {\n for (const plot of this.plots) {\n plot.values.set(bar, Number.NaN);\n plot.colors.set(bar, 0);\n }\n for (const shape of this.shapes) shape.on.set(bar, 0);\n for (const fill of this.fills) fill.colors.set(bar, 0);\n for (const background of this.backgrounds) background.colors.set(bar, 0);\n for (const condition of this.conditions) condition.on.set(bar, 0);\n for (const colors of this.barColorSlots) colors.set(bar, 0);\n });\n }\n\n /** No more plots, marks or levels: the setup is over. */\n close(): void {\n this.open = false;\n }\n\n private declaring(what: string): void {\n if (!this.open) throw new Error(`${what} is declared in the script's setup, not on a bar`);\n }\n\n /** A colour's place in the palette plus one. */\n private colorIndex(color: string): number {\n let index = this.paletteIndex.get(color);\n if (index === undefined) {\n if (this.palette.length >= MAX_COLORS) throw new Error(`a script gives its bars at most ${MAX_COLORS} colours`);\n this.palette.push(color);\n index = this.palette.length;\n this.paletteIndex.set(color, index);\n }\n return index;\n }\n\n plot(title: string, options: PlotOptions = {}): PlotHandle {\n this.declaring('plot');\n const slot: PlotSlot = {\n declaration: { title, kind: options.kind ?? 'line', ...(options.color ? { color: options.color } : {}), ...(options.width ? { width: options.width } : {}) },\n values: floatColumn(),\n colors: colorColumn(),\n };\n this.plots.push(slot);\n const handle: PlotHandle = {\n set: (value, color) => {\n slot.values.set(this.scope.bar, Number.isFinite(value) ? value : Number.NaN);\n if (color !== undefined) slot.colors.set(this.scope.bar, this.colorIndex(color));\n return value;\n },\n };\n this.handles.set(handle, this.plots.length - 1);\n return handle;\n }\n\n shape(title: string, options: ShapeOptions = {}): ShapeHandle {\n this.declaring('shape');\n const slot: ShapeSlot = {\n declaration: { title, shape: options.shape ?? 'triangleUp', position: options.position ?? 'belowBar', ...(options.color ? { color: options.color } : {}) },\n on: flagColumn(),\n };\n this.shapes.push(slot);\n return {\n set: (on) => {\n slot.on.set(this.scope.bar, on ? 1 : 0);\n return on;\n },\n };\n }\n\n fill(a: PlotHandle, b: PlotHandle, options: FillOptions = {}): FillHandle {\n this.declaring('fill');\n const first = this.handles.get(a);\n const second = this.handles.get(b);\n if (first === undefined || second === undefined) throw new Error('fill is between two plots of the same script');\n const slot: ColorSlot<FillDeclaration> = {\n declaration: { between: [first, second], ...(options.color ? { color: options.color } : {}) },\n colors: colorColumn(),\n };\n this.fills.push(slot);\n return {\n set: (color) => {\n slot.colors.set(this.scope.bar, color === undefined ? 0 : this.colorIndex(color));\n },\n };\n }\n\n bgcolor(options: BackgroundOptions = {}): BackgroundHandle {\n this.declaring('bgcolor');\n const slot: ColorSlot<BackgroundDeclaration> = { declaration: { title: options.title ?? 'Background' }, colors: colorColumn() };\n this.backgrounds.push(slot);\n return {\n set: (color) => {\n slot.colors.set(this.scope.bar, color === undefined ? 0 : this.colorIndex(color));\n },\n };\n }\n\n /** Shapes the script draws, listed with its output. */\n addDrawings(list: ScriptDrawings): ScriptDrawings {\n this.drawingLists.push(list);\n return list;\n }\n\n barcolor(): BarColorHandle {\n this.declaring('barcolor');\n const colors = colorColumn();\n this.barColorSlots.push(colors);\n return {\n set: (color) => {\n colors.set(this.scope.bar, color === undefined ? 0 : this.colorIndex(color));\n },\n };\n }\n\n alertCondition(title: string, options: AlertConditionOptions = {}): AlertConditionHandle {\n this.declaring('alertCondition');\n const slot = { declaration: { title, ...(options.message ? { message: options.message } : {}) }, on: flagColumn() };\n this.conditions.push(slot);\n return {\n set: (on) => {\n slot.on.set(this.scope.bar, on ? 1 : 0);\n return on;\n },\n };\n }\n\n hline(price: number, options: HlineOptions = {}): void {\n this.declaring('hline');\n this.levels.push({ price, ...options });\n }\n\n declarations(overlay: boolean): ScriptDeclarations {\n return {\n overlay,\n plots: this.plots.map((p) => p.declaration),\n shapes: this.shapes.map((s) => s.declaration),\n levels: [...this.levels],\n fills: this.fills.map((f) => f.declaration),\n backgrounds: this.backgrounds.map((b) => b.declaration),\n barColors: this.barColorSlots.length,\n alertConditions: this.conditions.map((c) => c.declaration),\n };\n }\n\n output(length: number, errors: readonly ScriptError[]): ScriptOutput {\n return {\n length,\n plots: this.plots.map((p) => ({ ...p.declaration, values: p.values.view(length), colors: p.colors.view(length) })),\n shapes: this.shapes.map((s) => ({ ...s.declaration, on: s.on.view(length) })),\n levels: [...this.levels],\n fills: this.fills.map((f) => ({ ...f.declaration, colors: f.colors.view(length) })),\n backgrounds: this.backgrounds.map((b) => ({ ...b.declaration, colors: b.colors.view(length) })),\n barColors: this.barColorSlots.map((colors) => colors.view(length)),\n alertConditions: this.conditions.map((c) => ({ ...c.declaration, on: c.on.view(length) })),\n palette: [...this.palette],\n drawings: this.drawingLists.flatMap((list) => list.list()),\n errors: [...errors],\n };\n }\n}\n","/**\n * What a script keeps from bar to bar, and how its live bar is run again.\n *\n * A run goes over the closed bars once, then runs its last bar (the one still\n * trading) again on each tick. Every piece of state a script makes in setup\n * (a `ta` sum, a kept value, a list) registers here, so the run can keep it\n * as it was when the live bar began (`commit`) and put it back before the\n * bar runs again (`rollback`). The closed bars are never run again, so their\n * state is not kept bar by bar: the run commits once, before the live bar.\n */\n\nimport type { ScriptLimitError, ScriptLimits } from './limits.js';\n\n/** A piece of a script's state the run keeps and puts back. */\nexport interface Unit {\n /** Keep the state as it is now: the live bar will start again from here. */\n commit(): void;\n /** Put back the state kept last. */\n rollback(): void;\n}\n\nexport interface Scope {\n readonly units: Unit[];\n /**\n * Whether the bar being run is the live one, run again on each tick. Only\n * then a list records how to undo what it does.\n */\n live: boolean;\n /** The bar being run, by its index. */\n bar: number;\n /** What empties a value a bar the script writes, before a bar is run (again). */\n readonly clearers: ((bar: number) => void)[];\n /** How far the run may go. */\n readonly limits: Readonly<Required<ScriptLimits>>;\n /** The loop steps the bar being run has taken. */\n steps: number;\n /** The limit the bar being run went past, caught by the script or not; null: none. */\n breach: ScriptLimitError | null;\n}\n\nlet active: Scope | null = null;\n\n/** Run `fn` with `scope` taking the state made meanwhile. */\nexport function inScope<T>(scope: Scope, fn: () => T): T {\n const outer = active;\n active = scope;\n try {\n return fn();\n } finally {\n active = outer;\n }\n}\n\n/** The scope a script's setup is running in. */\nexport function currentScope(what = 'ta and state'): Scope {\n if (!active) throw new Error(`${what} are made in a script's setup, not on a bar: each keeps the state of one script`);\n return active;\n}\n\n/** A set of numbers the run keeps and puts back as one. */\nexport function cell<T extends Record<string, number>>(init: T): T {\n const live = { ...init };\n const kept = { ...init };\n currentScope().units.push({\n commit: () => Object.assign(kept, live),\n rollback: () => Object.assign(live, kept),\n });\n return live;\n}\n","import type { Scope } from './scope.js';\n\n/** How far a run may go before the script is stopped, at the bar that went past. */\nexport interface ScriptLimits {\n /** The most loop steps one bar takes, each counted by `loop()`. Default 1,000,000. */\n loopSteps?: number;\n /** The most numbers one `state.array` holds. Default 100,000. */\n arraySize?: number;\n /**\n * The most ms one `load`, `tick` or `next` runs for, read after each bar.\n * Unset: no limit. A bar that never returns is not stopped by this: only\n * a worker can be stopped from outside.\n */\n runMs?: number;\n}\n\n/** Which limit a script went past. */\nexport type ScriptLimit = 'loop' | 'array' | 'time';\n\nexport const DEFAULT_LIMITS: Readonly<Required<ScriptLimits>> = {\n loopSteps: 1_000_000,\n arraySize: 100_000,\n runMs: Number.POSITIVE_INFINITY,\n};\n\n/** A limit gone past: what stops the bar. */\nexport class ScriptLimitError extends Error {\n constructor(readonly limit: ScriptLimit, message: string) {\n super(message);\n this.name = 'ScriptLimitError';\n }\n}\n\n/** The limits given, each checked, the rest at their defaults. */\nexport function limitsOf(given: ScriptLimits = {}): Required<ScriptLimits> {\n // A key given as undefined is unset, not a value to check.\n const set = Object.fromEntries(Object.entries(given).filter(([, value]) => value !== undefined));\n const limits = { ...DEFAULT_LIMITS, ...set };\n for (const key of Object.keys(DEFAULT_LIMITS) as (keyof ScriptLimits)[]) {\n const value = limits[key];\n if (typeof value !== 'number' || Number.isNaN(value) || value <= 0) {\n throw new RangeError(`script limits: ${key} must be a positive number, not ${String(value)}`);\n }\n }\n return limits;\n}\n\n/**\n * Stop the bar for `limit`. The run keeps it too, so a script that catches\n * the error and goes on is stopped all the same once the bar returns.\n */\nexport function overLimit(scope: Scope, limit: ScriptLimit, message: string): never {\n const error = new ScriptLimitError(limit, message);\n scope.breach ??= error;\n throw error;\n}\n","import { floatColumn } from './Column.js';\nimport { overLimit } from './limits.js';\nimport { currentScope, type Scope } from './scope.js';\n\n/** A value kept from bar to bar: what a bar leaves in it, the next bar finds. */\nexport interface Var<T> {\n value: T;\n}\n\n/**\n * A value kept from bar to bar, put back to the bar before's when the live\n * bar runs again. An object is put back as the same object: keep a handle\n * in one (a line drawn), and change a list through `state.array`.\n */\nexport function keep<T>(init: T): Var<T> {\n const scope = currentScope('state.var');\n const cell = { value: init };\n let kept = init;\n scope.units.push({\n commit: () => {\n kept = cell.value;\n },\n rollback: () => {\n cell.value = kept;\n },\n });\n return cell;\n}\n\n/** A value a bar the script sets and reads back (`at(1)`: the bar before's). */\nexport interface ScriptSeries {\n /** Set this bar's value; returns it. */\n set(value: number): number;\n /** The value `back` bars ago (0: this bar's); NaN where none was set. */\n at(back?: number): number;\n}\n\nexport function seriesOf(): ScriptSeries {\n const scope = currentScope('state.series');\n const column = floatColumn();\n scope.clearers.push((bar) => column.set(bar, Number.NaN));\n return {\n set: (value) => {\n column.set(scope.bar, value);\n return value;\n },\n // Never a bar ahead: a bar reads only itself and the bars before it.\n at: (back = 0) => (back >= 0 ? column.get(scope.bar - Math.floor(back)) : Number.NaN),\n };\n}\n\n/**\n * A list kept from bar to bar. On the live bar it records how to undo each\n * change, so a tick that runs the bar again starts from the list as the bar\n * before left it; on the closed bars it records nothing.\n */\nexport class ScriptArray {\n private items: number[] = [];\n private undo: (() => void)[] = [];\n\n constructor(private readonly scope: Scope) {\n scope.units.push({\n commit: () => {\n this.undo = [];\n },\n rollback: () => {\n for (let i = this.undo.length - 1; i >= 0; i--) this.undo[i]();\n this.undo = [];\n },\n });\n }\n\n private record(step: () => void): void {\n if (this.scope.live) this.undo.push(step);\n }\n\n /** Room for one more number, or the bar stops. */\n private grow(): void {\n const most = this.scope.limits.arraySize;\n if (this.items.length >= most) overLimit(this.scope, 'array', `a list holds at most ${most} numbers`);\n }\n\n size(): number {\n return this.items.length;\n }\n\n /** The value at `index` (negative: from the end); NaN outside the list. */\n get(index: number): number {\n const at = index < 0 ? this.items.length + index : index;\n return at >= 0 && at < this.items.length ? this.items[at] : Number.NaN;\n }\n\n set(index: number, value: number): void {\n if (index < 0 || index >= this.items.length) throw new RangeError(`array.set: index ${index} is outside a list of ${this.items.length}`);\n const before = this.items[index];\n this.items[index] = value;\n this.record(() => {\n this.items[index] = before;\n });\n }\n\n push(value: number): void {\n this.grow();\n this.items.push(value);\n this.record(() => {\n this.items.pop();\n });\n }\n\n pop(): number {\n if (this.items.length === 0) return Number.NaN;\n const value = this.items.pop()!;\n this.record(() => {\n this.items.push(value);\n });\n return value;\n }\n\n shift(): number {\n if (this.items.length === 0) return Number.NaN;\n const value = this.items.shift()!;\n this.record(() => {\n this.items.unshift(value);\n });\n return value;\n }\n\n unshift(value: number): void {\n this.grow();\n this.items.unshift(value);\n this.record(() => {\n this.items.shift();\n });\n }\n\n clear(): void {\n const before = this.items;\n this.items = [];\n this.record(() => {\n this.items = before;\n });\n }\n\n /** A copy of the values. */\n toArray(): number[] {\n return [...this.items];\n }\n\n sum(): number {\n let total = 0;\n for (const v of this.items) total += v;\n return total;\n }\n\n avg(): number {\n return this.items.length > 0 ? this.sum() / this.items.length : Number.NaN;\n }\n\n min(): number {\n return this.items.reduce((best, v) => (v < best ? v : best), this.items.length > 0 ? Infinity : Number.NaN);\n }\n\n max(): number {\n return this.items.reduce((best, v) => (v > best ? v : best), this.items.length > 0 ? -Infinity : Number.NaN);\n }\n\n /** The middle value, or the mean of the two middle ones. */\n median(): number {\n const n = this.items.length;\n if (n === 0) return Number.NaN;\n const sorted = [...this.items].sort((a, b) => a - b);\n const mid = n >> 1;\n return n % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;\n }\n}\n\nexport function arrayOf(): ScriptArray {\n return new ScriptArray(currentScope('state.array'));\n}\n","import type {\n IndicatorBoxDrawing,\n IndicatorDrawing,\n IndicatorLabelDrawing,\n IndicatorLineDrawing,\n IndicatorPoint,\n} from '@tradecanvas/commons';\nimport type { Scope } from './scope.js';\n\nexport type LabelProps = Omit<IndicatorLabelDrawing, 'kind'>;\nexport type LineProps = Omit<IndicatorLineDrawing, 'kind'>;\nexport type BoxProps = Omit<IndicatorBoxDrawing, 'kind'>;\n\n/** A shape a script drew: changed or taken away on a later bar. */\nexport interface DrawingHandle<P> {\n /** Change some of it; a shape taken away (by the script, or as the oldest past the limit) is left as it is. */\n set(changes: Partial<P>): void;\n /** Take it away. */\n remove(): void;\n}\n\n/** The most of each kind a script keeps; past it, the oldest goes. */\nexport interface DrawingLimits {\n /** Labels kept: default 50, at most 500. */\n maxLabels?: number;\n /** Lines kept: default 50, at most 500. */\n maxLines?: number;\n /** Boxes kept: default 50, at most 500. */\n maxBoxes?: number;\n}\n\ntype Kind = IndicatorDrawing['kind'];\n\n/** The most a script keeps of a kind unless it says otherwise, and the most it may ask for. */\nconst DEFAULT_MAX = 50;\nconst MOST = 500;\n\n/** A limit as asked, within 1 and the most; none asked (or not a number): the default. */\nconst limitOf = (asked: number | undefined) =>\n asked === undefined || Number.isNaN(asked) ? DEFAULT_MAX : Math.min(MOST, Math.max(1, Math.floor(asked)));\n\n/** Whether a point is a bar and a value: a script in plain JS may give anything. */\nconst isPoint = (p: unknown): p is IndicatorPoint =>\n !!p && typeof (p as IndicatorPoint).bar === 'number' && typeof (p as IndicatorPoint).value === 'number';\n\n/** The points a kind needs, by the field each is under. */\nconst POINTS: Record<Kind, readonly ('at' | 'from' | 'to')[]> = { label: ['at'], line: ['from', 'to'], box: ['from', 'to'] };\n\n/** Throws, for the script's error, when a shape lacks a point it needs. */\nfunction checked<D extends IndicatorDrawing>(drawing: D): D {\n for (const key of POINTS[drawing.kind]) {\n if (!isPoint((drawing as unknown as Record<string, unknown>)[key])) throw new Error(`a ${drawing.kind} needs ${key}: { bar, value }`);\n }\n return drawing;\n}\n\n/** A copy of a point, so the script changing its own object later changes nothing drawn. */\nconst pointOf = (p: IndicatorPoint): IndicatorPoint => ({ bar: p.bar, value: p.value });\n\n/** A drawing with its points its own. */\nfunction copied<D extends IndicatorDrawing>(drawing: D): D {\n const out: Record<string, unknown> = { ...drawing };\n for (const key of ['at', 'from', 'to'] as const) {\n const point = out[key] as IndicatorPoint | undefined;\n if (point) out[key] = pointOf(point);\n }\n return out as unknown as D;\n}\n\n/**\n * The labels, lines and boxes a script draws, kept from bar to bar. On the\n * live bar it records how to undo each change, so a tick that runs the bar\n * again starts from the shapes as the bar before left them.\n */\nexport class ScriptDrawings {\n /** By id: an id is the order made in. */\n private readonly items = new Map<number, IndicatorDrawing>();\n private readonly order: Record<Kind, number[]> = { label: [], line: [], box: [] };\n private readonly limits: Record<Kind, number>;\n private nextId = 0;\n private undo: (() => void)[] = [];\n\n constructor(private readonly scope: Scope, limits: DrawingLimits = {}) {\n this.limits = { label: limitOf(limits.maxLabels), line: limitOf(limits.maxLines), box: limitOf(limits.maxBoxes) };\n scope.units.push({\n commit: () => {\n this.undo = [];\n },\n rollback: () => {\n for (let i = this.undo.length - 1; i >= 0; i--) this.undo[i]();\n this.undo = [];\n },\n });\n }\n\n label(props: LabelProps): DrawingHandle<LabelProps> {\n return this.add({ kind: 'label', ...props });\n }\n\n line(props: LineProps): DrawingHandle<LineProps> {\n return this.add({ kind: 'line', ...props });\n }\n\n box(props: BoxProps): DrawingHandle<BoxProps> {\n return this.add({ kind: 'box', ...props });\n }\n\n /** The shapes kept, in the order made. */\n list(): IndicatorDrawing[] {\n return [...this.items.keys()].sort((a, b) => a - b).map((id) => this.items.get(id)!);\n }\n\n private record(step: () => void): void {\n if (this.scope.live) this.undo.push(step);\n }\n\n private add<D extends IndicatorDrawing>(drawing: D): DrawingHandle<Omit<D, 'kind'>> {\n checked(drawing);\n const id = this.nextId++;\n this.record(() => {\n this.nextId = id;\n });\n this.items.set(id, copied(drawing));\n this.record(() => {\n this.items.delete(id);\n });\n const ids = this.order[drawing.kind];\n ids.push(id);\n this.record(() => {\n ids.pop();\n });\n while (ids.length > this.limits[drawing.kind]) {\n const oldest = ids.shift()!;\n const item = this.items.get(oldest)!;\n this.items.delete(oldest);\n this.record(() => {\n this.items.set(oldest, item);\n ids.unshift(oldest);\n });\n }\n return {\n set: (changes) => this.change(id, changes as Partial<IndicatorDrawing>),\n remove: () => this.remove(id),\n };\n }\n\n private change(id: number, changes: Partial<IndicatorDrawing>): void {\n const before = this.items.get(id);\n if (!before) return;\n this.items.set(id, copied(checked({ ...before, ...changes, kind: before.kind } as IndicatorDrawing)));\n this.record(() => {\n this.items.set(id, before);\n });\n }\n\n private remove(id: number): void {\n const before = this.items.get(id);\n if (!before) return;\n this.items.delete(id);\n const ids = this.order[before.kind];\n const at = ids.indexOf(id);\n if (at >= 0) ids.splice(at, 1);\n this.record(() => {\n this.items.set(id, before);\n if (at >= 0) ids.splice(at, 0, id);\n });\n }\n}\n","import type { OHLCBar, TimeFrame } from '@tradecanvas/commons';\nimport { timeframeToMs } from '@tradecanvas/commons';\nimport { periodKeyer } from '@tradecanvas/core';\nimport { defineScript, type ScriptBar, type ScriptPrices } from './defineScript.js';\nimport { ScriptLimitError, type ScriptLimits } from './limits.js';\nimport { ScriptRun } from './ScriptRun.js';\nimport type { ScriptArray, ScriptSeries, Var } from './state.js';\n\n/** What a higher interval's setup is given: its own bars' prices and state. */\nexport interface SecuritySetupApi {\n /** The higher interval's bars, read back from the one being run. Their time is their first chart bar's. */\n readonly prices: ScriptPrices;\n readonly state: {\n var<T>(init: T): Var<T>;\n array(): ScriptArray;\n series(): ScriptSeries;\n };\n}\n\n/** Run once, before the first bar of the higher interval: makes its sums, returns its value a bar. */\nexport type SecuritySetup = (api: SecuritySetupApi) => (bar: ScriptBar) => number;\n\nexport interface SecurityOptions {\n /**\n * Also the bar of the higher interval still forming, as it was at each\n * bar: its bars so far. It changes on the chart's bars as they come, as\n * the forming bar does (it repaints). Unset: only bars that closed.\n */\n live?: boolean;\n}\n\n/** Where the chart's bars are read and the higher interval is cut. */\nexport interface SecurityContext {\n /** The bars loaded, for the keyer to read their clock (seconds or ms, daily) and their spacing. */\n timeline(): readonly { time: number }[];\n /** The chart's bar `index` as it now is (the bar before, closed, when a new one comes). */\n barAt(index: number): ScriptBar;\n /** The exchange's zone and the trading day's start, for days and longer. */\n exchangeTimeZone?: string;\n sessionStart?: number;\n /** The script's limits, which the higher interval's run keeps to as well (its loops and lists; the time is the script's). */\n limits?: ScriptLimits;\n /** Told of a limit the higher interval went past, so the script stops even if it catches the error. */\n onLimit?(error: ScriptLimitError): void;\n}\n\ninterface Bucket {\n open: number;\n high: number;\n low: number;\n close: number;\n volume: number;\n}\n\n/** Times under this are seconds since the epoch, not ms (one in 1973 is past it in ms). */\nconst SECONDS_BELOW = 1e11;\n\nconst merged = (before: Bucket | null, bar: ScriptBar): Bucket =>\n before\n ? { open: before.open, high: Math.max(before.high, bar.high), low: Math.min(before.low, bar.low), close: bar.close, volume: before.volume + bar.volume }\n : { open: bar.open, high: bar.high, low: bar.low, close: bar.close, volume: bar.volume };\n\nconst same = (a: Bucket | null, b: Bucket): boolean =>\n !!a && a.open === b.open && a.high === b.high && a.low === b.low && a.close === b.close && a.volume === b.volume;\n\n/** The chart's bar spacing in ms, the smallest between its bars; NaN with fewer than two. */\nfunction spacingMs(timeline: readonly { time: number }[]): number {\n let least = Infinity;\n for (let i = 1; i < timeline.length; i++) least = Math.min(least, timeline[i].time - timeline[i - 1].time);\n if (!Number.isFinite(least) || least <= 0) return Number.NaN;\n return timeline[timeline.length - 1].time < SECONDS_BELOW ? least * 1000 : least;\n}\n\n/**\n * A value of a higher interval of the same symbol, a chart bar at a time:\n * the higher interval's bars are made of the chart's own (as a resample\n * cuts them), and `setup`'s sums run over them in a run of their own, the\n * forming bar run again as a tick is. Each chart bar reads, by default, the\n * value of the last bar of the higher interval that closed before its own\n * (it never changes after); with `live`, the forming bar's as it was then.\n * Neither reads a bar after the chart's own. Called on every bar, as a `ta`\n * sum is.\n */\nexport function securityOf(\n context: SecurityContext,\n interval: TimeFrame,\n setup: SecuritySetup,\n options: SecurityOptions = {},\n): (bar: ScriptBar) => number {\n const span = typeof interval === 'string' ? timeframeToMs(interval) : Number.NaN;\n if (!Number.isFinite(span)) {\n throw new Error(`request.security: '${String(interval)}' is no interval it can read: a count and a unit, as '15m', '1h', '4h', '1d', '1w', '1M' (case matters)`);\n }\n const results: number[] = [];\n /** Whether the chart bar the higher bar is run for is the live one: the higher bar is live only then. */\n let chartLive = false;\n const sub = new ScriptRun(defineScript({\n id: `security:${interval}`,\n name: interval,\n setup(api) {\n const onBar = setup({ prices: api.prices, state: api.state });\n return (bar) => {\n // The higher bar that closes as a new one opens is closed, whatever the chart's bar is.\n results[bar.index] = onBar(bar.live && !chartLive ? { ...bar, live: false } : bar);\n };\n },\n }), {}, context.limits ? { limits: { loopSteps: context.limits.loopSteps, arraySize: context.limits.arraySize } } : {});\n let keyOf: ((time: number) => number) | null = null;\n let lastIndex = -1;\n let key = Number.NaN;\n /** The forming bucket's time: its first chart bar's, in the chart's unit. */\n let time = Number.NaN;\n /** The forming bar of the higher interval before the chart's last bar, and with it as last run. */\n let before: Bucket | null = null;\n let now: Bucket | null = null;\n /** The higher bars kept: one the nested run has past these was added by a call that then threw. */\n let buckets = 0;\n\n const run = (bucket: Bucket, at: number, fresh: boolean) => {\n const higher: OHLCBar = { time: at, ...bucket };\n if (sub.length === 0) sub.load([higher]);\n else if (fresh && sub.length === buckets) sub.next(higher);\n // Not fresh, or added already by the call that threw: the bar again, as a tick.\n else sub.tick(higher);\n const error = sub.errors[0];\n if (!error) return;\n const message = `request.security('${interval}'), on its bar ${error.bar}: ${error.message}`;\n if (!error.limit) throw new Error(message);\n const breach = new ScriptLimitError(error.limit, message);\n context.onLimit?.(breach);\n throw breach;\n };\n\n /** The keyer, made at the first bar, once the chart's spacing says the interval is higher. */\n const keyer = () => {\n if (keyOf) return keyOf;\n const timeline = context.timeline();\n const spacing = spacingMs(timeline);\n if (Number.isFinite(spacing) && span < spacing) {\n throw new Error(`request.security('${interval}') reads a higher interval than the chart's bars: they are ${spacing / 60_000} minutes apart`);\n }\n keyOf = periodKeyer(timeline, interval, context.exchangeTimeZone, context.sessionStart);\n return keyOf;\n };\n\n return (bar) => {\n const keyOfTime = keyer();\n chartLive = bar.live;\n if (bar.index === lastIndex) {\n // The live bar again (a tick): the forming bar rebuilt from what came before it.\n if (keyOfTime(bar.time) !== key) throw new Error(`request.security('${interval}'): the live bar's time moved to another period; load the bars again`);\n const bucket = merged(before, bar);\n run(bucket, time, false);\n now = bucket;\n } else if (bar.index === lastIndex + 1) {\n if (lastIndex >= 0) {\n // The bar before as it closed: a tick that skipped this call, or threw before it, left `now` behind.\n const closed = merged(before, context.barAt(lastIndex));\n chartLive = false;\n if (!same(now, closed)) run(closed, time, false);\n chartLive = bar.live;\n now = closed;\n }\n const barKey = keyOfTime(bar.time);\n const fresh = barKey !== key || now === null;\n const nextBefore = fresh ? null : now;\n const bucket = merged(nextBefore, bar);\n const at = fresh ? bar.time : time;\n run(bucket, at, fresh);\n // Kept once it ran: a bar that throws is met again as the same bar, not merged into itself.\n key = barKey;\n time = at;\n before = nextBefore;\n now = bucket;\n lastIndex = bar.index;\n buckets = sub.length;\n } else {\n throw new Error(`request.security('${interval}') is called on every bar: it was not on bar ${lastIndex + 1}`);\n }\n const forming = sub.length - 1;\n const value = options.live ? results[forming] : results[forming - 1];\n return value === undefined ? Number.NaN : value;\n };\n}\n","import type { OHLCBar, TimeFrame } from '@tradecanvas/commons';\nimport { floatColumn, type Column } from './Column.js';\nimport { inputValue, type OnBar, type PriceSeries, type Script, type ScriptBar, type ScriptChart, type ScriptInputs, type ScriptPrices } from './defineScript.js';\nimport { Outputs, type ScriptDeclarations, type ScriptError, type ScriptOutput } from './outputs.js';\nimport { currentScope, inScope, type Scope } from './scope.js';\nimport { arrayOf, keep, seriesOf } from './state.js';\nimport { ScriptDrawings } from './drawings.js';\nimport { securityOf } from './security.js';\nimport { limitsOf, overLimit, ScriptLimitError, type ScriptLimits } from './limits.js';\n\nconst PRICES = ['time', 'open', 'high', 'low', 'close', 'volume'] as const;\ntype Price = (typeof PRICES)[number];\n\n/** Where a run's days are counted, for a higher interval of days or longer. */\nexport interface ScriptRunOptions {\n /** The exchange's IANA zone (`'Asia/Ho_Chi_Minh'`); unset: UTC. */\n exchangeTimeZone?: string;\n /** Minutes after midnight the trading day starts at (a 17:00 open: 1020); unset: midnight. */\n sessionStart?: number;\n /** The chart's interval (`'5m'`), which the script may read; unset: not known. */\n interval?: TimeFrame;\n /** How far the run may go: loop steps a bar, numbers a list, ms a run. */\n limits?: ScriptLimits;\n}\n\n/** What `update` did with a bar: ran the live bar again, ran a new bar, or nothing (an older bar: load the bars again). */\nexport type UpdateKind = 'tick' | 'bar' | 'reload';\n\n/**\n * A script run over bars. `load` runs every bar; the last one stays live:\n * `tick` runs it again from the state the bar before left, `next` closes it\n * and runs a new bar. A tick costs one bar, whatever the bars before.\n */\nexport class ScriptRun {\n private scope!: Scope;\n private outputs!: Outputs;\n private onBar!: OnBar;\n private prices!: Record<Price, Column<Float64Array>>;\n private count = 0;\n private failures: ScriptError[] = [];\n /** The bar the script threw on, after which no bar runs; -1: none. */\n private haltedAt = -1;\n private declared!: ScriptDeclarations;\n /** Whether no bar has run since the setup: a load needs no setup of its own. */\n private fresh = false;\n\n /** What it draws, known from its setup. */\n get declarations(): ScriptDeclarations {\n return this.declared;\n }\n\n /** The bars loaded last: what a higher interval reads the bars' clock from. */\n private loaded: readonly OHLCBar[] = [];\n private readonly limits: Readonly<Required<ScriptLimits>>;\n /** When the `load`, `tick` or `next` running began, by `performance.now()`. */\n private began = 0;\n private intervalRead = false;\n\n constructor(\n private readonly script: Script<ScriptInputs>,\n private readonly params: Readonly<Record<string, unknown>> = {},\n private readonly options: ScriptRunOptions = {},\n ) {\n this.limits = limitsOf(options.limits);\n this.start();\n }\n\n /** Where the script stopped, and why: none while it runs. */\n get errors(): readonly ScriptError[] {\n return this.failures;\n }\n\n /** How many bars it has run. */\n get length(): number {\n return this.count;\n }\n\n get output(): ScriptOutput {\n return this.outputs.output(this.count, this.failures);\n }\n\n /** Run all of `bars` from the start; the last one stays live. */\n load(bars: readonly OHLCBar[]): void {\n this.loaded = bars;\n if (!this.fresh) this.start();\n this.fresh = false;\n this.clockIn();\n for (let i = 0; i < bars.length; i++) {\n if (i === bars.length - 1) this.goLive();\n this.write(i, bars[i]);\n this.count = i + 1;\n this.runBar(i);\n }\n }\n\n /** The live bar as it now is: run it again from the state the bar before left. */\n tick(bar: OHLCBar): void {\n if (this.count === 0) return this.load([bar]);\n this.fresh = false;\n this.clockIn();\n const i = this.count - 1;\n this.write(i, bar);\n for (const unit of this.scope.units) unit.rollback();\n if (this.haltedAt === i) {\n this.haltedAt = -1;\n this.failures = this.failures.filter((error) => error.bar !== i);\n }\n this.runBar(i);\n }\n\n /**\n * Close the live bar, run once more as a closed one (`bar.live` false) so\n * a feed ends where loading its bars does, and run `bar` as the new live\n * one. A script that threw on the live bar stays stopped once it closes,\n * as on any closed bar: load the bars again to run it anew.\n */\n next(bar: OHLCBar): void {\n if (this.count === 0) return this.load([bar]);\n this.fresh = false;\n this.clockIn();\n this.closeLive();\n this.goLive();\n const i = this.count;\n this.write(i, bar);\n this.count = i + 1;\n this.runBar(i);\n }\n\n /** 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. */\n update(bar: OHLCBar): UpdateKind {\n if (this.count === 0) {\n this.load([bar]);\n return 'bar';\n }\n const live = this.prices.time.get(this.count - 1);\n if (bar.time === live) {\n this.tick(bar);\n return 'tick';\n }\n if (bar.time > live) {\n this.next(bar);\n return 'bar';\n }\n return 'reload';\n }\n\n /** Begin again from no bars: a new setup, new state. */\n private start(): void {\n const scope: Scope = { units: [], live: false, bar: 0, clearers: [], limits: this.limits, steps: 0, breach: null };\n this.scope = scope;\n this.prices = Object.fromEntries(PRICES.map((p) => [p, floatColumn()])) as Record<Price, Column<Float64Array>>;\n this.outputs = new Outputs(scope);\n this.count = 0;\n this.failures = [];\n this.haltedAt = -1;\n const declared = this.script.inputs ?? {};\n const inputs = Object.fromEntries(Object.keys(declared).map((name) => [name, inputValue(this.params[name], declared[name])]));\n this.onBar = inScope(scope, () => this.script.setup({\n inputs: inputs as never,\n chart: this.chart(),\n prices: this.priceSeries(),\n plot: (title, options) => this.outputs.plot(title, options),\n loop: () => {\n if (++scope.steps > scope.limits.loopSteps) overLimit(scope, 'loop', `a bar takes at most ${scope.limits.loopSteps} loop steps`);\n },\n shape: (title, options) => this.outputs.shape(title, options),\n fill: (a, b, options) => this.outputs.fill(a, b, options),\n bgcolor: (options) => this.outputs.bgcolor(options),\n barcolor: () => this.outputs.barcolor(),\n alertCondition: (title, options) => this.outputs.alertCondition(title, options),\n drawings: (limits) => this.outputs.addDrawings(new ScriptDrawings(currentScope('drawings'), limits)),\n request: {\n security: (interval, setup, options) => {\n // Only in setup: its run belongs to the script.\n const scope = currentScope('request.security');\n const context = {\n timeline: () => this.loaded,\n barAt: (i: number) => this.barAt(i),\n ...this.options,\n limits: this.limits,\n onLimit: (error: ScriptLimitError) => {\n scope.breach ??= error;\n },\n };\n return securityOf(context, interval, setup, options);\n },\n },\n hline: (price, options) => this.outputs.hline(price, options),\n state: { var: keep, array: arrayOf, series: seriesOf },\n }));\n this.outputs.close();\n if (typeof this.onBar !== 'function') throw new Error(`script '${this.script.id}': setup must return what each bar runs`);\n this.declared = this.outputs.declarations(this.script.overlay === true);\n this.fresh = true;\n }\n\n /** The chart as the script reads it, noting that the interval was. */\n private chart(): ScriptChart {\n const { exchangeTimeZone = 'UTC', interval = null } = this.options;\n const read = () => {\n this.intervalRead = true;\n return interval;\n };\n return Object.freeze({\n timeZone: exchangeTimeZone,\n get interval() {\n return read();\n },\n });\n }\n\n /** Whether the script has read the chart's interval: in its setup, for one that has run no bar. */\n get readsInterval(): boolean {\n return this.intervalRead;\n }\n\n /** From here on the bar run is the live one: keep the state the bars before left. */\n private goLive(): void {\n for (const unit of this.scope.units) unit.commit();\n this.scope.live = true;\n }\n\n /** The live bar as it closed: run from the state the bar before left, as the closed bar it now is. */\n private closeLive(): void {\n // One it threw on stays as it stopped there.\n if (this.haltedAt >= 0) return;\n for (const unit of this.scope.units) unit.rollback();\n this.scope.live = false;\n this.runBar(this.count - 1);\n }\n\n private priceSeries(): ScriptPrices {\n const read = (price: Price): PriceSeries => ({\n // Never a bar ahead: a bar sees only itself and the bars before it.\n at: (back = 0) => (back >= 0 ? this.prices[price].get(this.scope.bar - Math.floor(back)) : Number.NaN),\n });\n return Object.fromEntries(PRICES.map((p) => [p, read(p)])) as unknown as ScriptPrices;\n }\n\n private write(i: number, bar: OHLCBar): void {\n const p = this.prices;\n p.time.set(i, bar.time);\n p.open.set(i, bar.open);\n p.high.set(i, bar.high);\n p.low.set(i, bar.low);\n p.close.set(i, bar.close);\n p.volume.set(i, bar.volume ?? 0);\n }\n\n /** Bar `i` as its prices now stand. */\n private barAt(i: number): ScriptBar {\n const p = this.prices;\n return {\n index: i,\n time: p.time.get(i),\n open: p.open.get(i),\n high: p.high.get(i),\n low: p.low.get(i),\n close: p.close.get(i),\n volume: p.volume.get(i),\n live: this.scope.live && i === this.count - 1,\n };\n }\n\n private runBar(i: number): void {\n const scope = this.scope;\n scope.bar = i;\n for (const clear of scope.clearers) clear(i);\n if (this.haltedAt >= 0) return;\n const bar = this.barAt(i);\n scope.steps = 0;\n scope.breach = null;\n let failure: unknown = null;\n try {\n // Not in the scope: a sum or a kept value made on a bar is refused, not made again each bar.\n this.onBar(bar);\n } catch (error) {\n failure = error;\n }\n // A limit stops the bar even when the script caught it; the run's time is read once the bar is done.\n failure = scope.breach ?? failure ?? this.overTime();\n if (failure === null) return;\n this.haltedAt = i;\n const limit = failure instanceof ScriptLimitError ? { limit: failure.limit } : {};\n this.failures.push({ bar: i, message: failure instanceof Error ? failure.message : String(failure), ...limit });\n }\n\n /** Start the clock of a `load`, `tick` or `next`, when the run has a time. */\n private clockIn(): void {\n if (Number.isFinite(this.limits.runMs)) this.began = performance.now();\n }\n\n /** The time gone past, once a bar is done; null while within it. */\n private overTime(): ScriptLimitError | null {\n const most = this.limits.runMs;\n if (!Number.isFinite(most) || performance.now() - this.began <= most) return null;\n return new ScriptLimitError('time', `a run takes at most ${most} ms; it was past that at this bar`);\n }\n}\n","import { currentScope } from './scope.js';\n\n/**\n * The last values a sum was given, a missing one (NaN) included, so that\n * \"the value `n` calls back\" is where the whole series would have it.\n *\n * On the live bar it records each slot it writes over and puts it back on a\n * rollback: a tick that pushes and a later tick that does not (a condition\n * true, then false) still read what the bars before left.\n */\nexport class Ring {\n private readonly slots: Float64Array;\n private count = 0;\n private run = 0;\n private kept = { count: 0, run: 0 };\n /** The slots written over on the live bar, as [slot, value before], oldest first. */\n private overwritten: number[] = [];\n\n constructor(readonly size: number) {\n const scope = currentScope();\n this.slots = new Float64Array(size + 1).fill(Number.NaN);\n scope.units.push({\n commit: () => {\n this.kept = { count: this.count, run: this.run };\n this.overwritten = [];\n },\n rollback: () => {\n for (let i = this.overwritten.length - 2; i >= 0; i -= 2) this.slots[this.overwritten[i]] = this.overwritten[i + 1];\n this.overwritten = [];\n this.count = this.kept.count;\n this.run = this.kept.run;\n },\n });\n this.live = () => scope.live;\n }\n\n private readonly live: () => boolean;\n\n /** Take the next value. */\n push(value: number): void {\n const slot = this.count % this.slots.length;\n if (this.live()) this.overwritten.push(slot, this.slots[slot]);\n this.slots[slot] = value;\n this.count++;\n this.run = Number.isNaN(value) ? 0 : this.run + 1;\n }\n\n /** The value `back` values before the last one given (0: the last); NaN before the first. */\n at(back: number): number {\n const index = this.count - 1 - back;\n if (back < 0 || back > this.size || index < 0) return Number.NaN;\n return this.slots[index % this.slots.length];\n }\n\n /** How many values were given. */\n get given(): number {\n return this.count;\n }\n\n /** How many values in a row, up to the last, were numbers. */\n get numbersInRow(): number {\n return this.run;\n }\n}\n","import { cell } from '../scope.js';\n\n/** A value a sum takes: a number, or none (NaN) for anything that is not a finite number. */\nexport function num(value: number): number {\n return Number.isFinite(value) ? value : Number.NaN;\n}\n\n/** A period of at least one, as the built-in indicators take one: its whole part. */\nexport function whole(period: number): number {\n return Number.isFinite(period) ? Math.max(1, Math.floor(period)) : 1;\n}\n\n/** A sum a bar at a time: given this bar's value, it gives this bar's result. */\nexport type Step = (value: number) => number;\n\n/** The prices of a bar a sum of ranges reads. */\nexport interface BarPrices {\n readonly high: number;\n readonly low: number;\n readonly close: number;\n}\n\n/**\n * A sum over a value a bar as `@tradecanvas/core`'s `ta` runs a built-in\n * indicator over one: from its first number on, a missing value is computed\n * over as the last number (no change on that bar) and gives none itself.\n */\nexport function holdGaps<T>(step: (value: number) => T, none: T): (value: number) => T {\n const state = cell({ last: Number.NaN });\n return (value) => {\n const v = num(value);\n if (!Number.isNaN(v)) {\n state.last = v;\n return step(v);\n }\n if (!Number.isNaN(state.last)) step(state.last);\n return none;\n };\n}\n\n/**\n * A bar's prices as the built-in indicators are given them: a close that is\n * no number is the close before, another price that is none is its close.\n */\nexport function cleanPrices(): (bar: BarPrices) => BarPrices {\n const state = cell({ close: Number.NaN });\n return (bar) => {\n const close = Number.isFinite(bar.close) ? bar.close : state.close;\n state.close = close;\n const price = (value: number) => (Number.isFinite(value) ? value : close);\n return { high: price(bar.high), low: price(bar.low), close };\n };\n}\n","import { Ring } from '../Ring.js';\nimport { cell } from '../scope.js';\nimport { holdGaps, num, whole, type Step } from './common.js';\n\n/*\n * Each sum here does, a bar at a time, the steps the whole-series sums of\n * `@tradecanvas/core` do (`math.ts`), in the same order, so the values are\n * the chart's own. A missing value (NaN) is handled as there: a simple or\n * weighted average needs `period` numbers in a row, a smoothing skips it.\n */\n\n/** Simple moving average of the last `period` values; a gap starts it again. */\nexport function sma(period: number): Step {\n const p = whole(period);\n const ring = new Ring(p);\n const state = cell({ sum: 0 });\n return (value) => {\n const v = num(value);\n ring.push(v);\n if (Number.isNaN(v)) {\n state.sum = 0;\n return Number.NaN;\n }\n state.sum += v;\n if (ring.numbersInRow > p) state.sum -= ring.at(p);\n return ring.numbersInRow >= p ? state.sum / p : Number.NaN;\n };\n}\n\n/** Starts as the simple average of the first `period` values, then moves `alpha` of the way to each new one; a gap keeps the value and gives none. */\nfunction smoothing(period: number, alpha: (p: number) => number): Step {\n const p = whole(period);\n const a = alpha(p);\n const state = cell({ seed: 0, count: 0, value: Number.NaN });\n return (value) => {\n const v = num(value);\n if (Number.isNaN(v)) return Number.NaN;\n if (Number.isNaN(state.value)) {\n state.seed += v;\n state.count++;\n if (state.count === p) state.value = state.seed / p;\n return state.value;\n }\n state.value += a * (v - state.value);\n return state.value;\n };\n}\n\n/** Exponential moving average, started as the simple average of its first `period` values. */\nexport function ema(period: number): Step {\n return smoothing(period, (p) => 2 / (p + 1));\n}\n\n/** Wilder's smoothing (RMA, SMMA): an EMA moving 1 / period of the way. */\nexport function rma(period: number): Step {\n return smoothing(period, (p) => 1 / p);\n}\n\n/** The last `period` values, oldest first, or null when one of them is missing. */\nexport function windowOf(ring: Ring, p: number): number[] | null {\n if (ring.given < p) return null;\n const values: number[] = new Array(p);\n for (let k = 0; k < p; k++) {\n const v = ring.at(p - 1 - k);\n if (Number.isNaN(v)) return null;\n values[k] = v;\n }\n return values;\n}\n\n/** Linearly weighted moving average: the newest of `period` values weighs `period`, the oldest 1. */\nexport function wma(period: number): Step {\n const p = whole(period);\n const ring = new Ring(p);\n const denominator = (p * (p + 1)) / 2;\n return (value) => {\n ring.push(num(value));\n const values = windowOf(ring, p);\n if (!values) return Number.NaN;\n let sum = 0;\n for (let k = 0; k < p; k++) sum += values[k] * (k + 1);\n return sum / denominator;\n };\n}\n\n/** Standard deviation of the whole population of the last `period` values. */\nexport function stdev(period: number): Step {\n const p = whole(period);\n const ring = new Ring(p);\n return (value) => {\n ring.push(num(value));\n const values = windowOf(ring, p);\n if (!values) return Number.NaN;\n let sum = 0;\n let sumSq = 0;\n for (const v of values) {\n sum += v;\n sumSq += v * v;\n }\n const mean = sum / p;\n return Math.sqrt(Math.max(0, sumSq / p - mean * mean));\n };\n}\n\n/** Hull moving average: a weighted average of twice the half-period one less the full one, over the root of the period (each at least 2), as the built-in HMA. */\nexport function hma(period: number): Step {\n return holdGaps(hullOf(period), Number.NaN);\n}\n\nfunction hullOf(period: number): Step {\n const p = Math.max(2, whole(period));\n const half = wma(Math.max(2, Math.floor(p / 2)));\n const full = wma(p);\n const smooth = wma(Math.max(2, Math.floor(Math.sqrt(p))));\n return (value) => {\n const h = half(value);\n const f = full(value);\n return smooth(Number.isNaN(h) || Number.isNaN(f) ? Number.NaN : 2 * h - f);\n };\n}\n\n/** Volume-weighted moving average of the last `period` bars, as the built-in VWMA: none while their volume is nothing. */\nexport function vwma(period: number): (value: number, volume: number) => number {\n const p = whole(period);\n const prices = new Ring(p);\n const volumes = new Ring(p);\n const state = cell({ pv: 0, volume: 0, last: Number.NaN });\n return (value, volume) => {\n // A missing price is computed over as the last one, and gives none itself.\n const given = num(value);\n if (!Number.isNaN(given)) state.last = given;\n const v = state.last;\n if (Number.isNaN(v)) return Number.NaN;\n const vol = Number.isFinite(volume) ? volume : 0;\n prices.push(v);\n volumes.push(vol);\n state.pv += v * vol;\n state.volume += vol;\n if (prices.given > p) {\n state.pv -= prices.at(p) * volumes.at(p);\n state.volume -= volumes.at(p);\n }\n if (Number.isNaN(given)) return Number.NaN;\n return prices.given >= p && state.volume > 0 ? state.pv / state.volume : Number.NaN;\n };\n}\n","import { Ring } from '../Ring.js';\nimport { cell } from '../scope.js';\nimport { num, whole, type Step } from './common.js';\n\n/** Whether `a` went from one side of `b` to the other since the bar before; `up`: from at or under it to over it. */\nfunction crossing(up: boolean): (a: number, b: number) => boolean {\n const state = cell({ a: Number.NaN, b: Number.NaN });\n return (aValue, bValue) => {\n const a = num(aValue);\n const b = num(bValue);\n const beforeA = state.a;\n const beforeB = state.b;\n state.a = a;\n state.b = b;\n if ([a, b, beforeA, beforeB].some(Number.isNaN)) return false;\n return up ? beforeA <= beforeB && a > b : beforeA >= beforeB && a < b;\n };\n}\n\n/** True on the bar where `a` goes over `b`: at or under it the bar before, over it now. */\nexport function crossover(): (a: number, b: number) => boolean {\n return crossing(true);\n}\n\n/** True on the bar where `a` goes under `b`: at or over it the bar before, under it now. */\nexport function crossunder(): (a: number, b: number) => boolean {\n return crossing(false);\n}\n\n/** True on the bar where `a` goes over or under `b`. */\nexport function cross(): (a: number, b: number) => boolean {\n const over = crossover();\n const under = crossunder();\n return (a, b) => {\n const up = over(a, b);\n const down = under(a, b);\n return up || down;\n };\n}\n\n/** A pivot `right` values back: strictly beyond the `left` values before it and the `right` after it, by `beyond`. */\nfunction pivot(left: number, right: number, beyond: (a: number, b: number) => boolean): Step {\n const l = whole(left);\n const r = whole(right);\n const ring = new Ring(l + r);\n return (value) => {\n ring.push(num(value));\n if (ring.given < l + r + 1) return Number.NaN;\n const center = ring.at(r);\n if (Number.isNaN(center)) return Number.NaN;\n for (let k = 0; k <= l + r; k++) {\n if (k === r) continue;\n const v = ring.at(k);\n if (Number.isNaN(v) || !beyond(center, v)) return Number.NaN;\n }\n return center;\n };\n}\n\n/** The high of a pivot `right` bars back: higher than the `left` before it and the `right` after it. NaN on other bars. */\nexport function pivothigh(left: number, right: number): Step {\n return pivot(left, right, (center, other) => center > other);\n}\n\n/** The low of a pivot `right` bars back: lower than the `left` before it and the `right` after it. NaN on other bars. */\nexport function pivotlow(left: number, right: number): Step {\n return pivot(left, right, (center, other) => center < other);\n}\n\n/** How many bars since the condition was last true (0 on a bar it is); NaN before it ever was. */\nexport function barssince(): (condition: boolean) => number {\n const state = cell({ since: Number.NaN });\n return (condition) => {\n state.since = condition ? 0 : state.since + 1;\n return state.since;\n };\n}\n\n/** The value on the bar of the condition's `occurrence`-th last true (0: the last); NaN until there is one. */\nexport function valuewhen(occurrence = 0): (condition: boolean, value: number) => number {\n const back = Math.max(0, Math.floor(occurrence));\n const seen = new Ring(back);\n return (condition, value) => {\n if (condition) seen.push(num(value));\n return seen.at(back);\n };\n}\n","import { Ring } from '../Ring.js';\nimport { cell } from '../scope.js';\nimport { ema, sma, stdev } from './averages.js';\nimport { holdGaps, num, whole, type Step } from './common.js';\n\n/** Relative Strength Index, 0 to 100, as the built-in RSI: Wilder's smoothing of the gains and losses, started as their simple average. */\nexport function rsi(period = 14): Step {\n return holdGaps(rsiOf(period), Number.NaN);\n}\n\nfunction rsiOf(period: number): Step {\n const p = whole(period);\n const state = cell({ prev: Number.NaN, count: 0, gain: 0, loss: 0 });\n const value = () => (state.loss === 0 ? 100 : 100 - 100 / (1 + state.gain / state.loss));\n return (input) => {\n const v = num(input);\n if (Number.isNaN(v)) return Number.NaN;\n if (Number.isNaN(state.prev)) {\n state.prev = v;\n return Number.NaN;\n }\n const change = v - state.prev;\n state.prev = v;\n const gain = change > 0 ? change : 0;\n const loss = change < 0 ? -change : 0;\n if (state.count < p) {\n state.gain += gain;\n state.loss += loss;\n state.count++;\n if (state.count < p) return Number.NaN;\n state.gain /= p;\n state.loss /= p;\n return value();\n }\n state.gain = (state.gain * (p - 1) + gain) / p;\n state.loss = (state.loss * (p - 1) + loss) / p;\n return value();\n };\n}\n\nexport interface MacdValue {\n readonly macd: number;\n readonly signal: number;\n readonly histogram: number;\n}\n\n/**\n * MACD: the fast average less the slow one, its signal line and the one less\n * the other. Its averages start as simple ones, as every EMA here does (the\n * built-in MACD indicator starts its own at the first close, so its first\n * hundred bars or so differ by a hair).\n */\nexport function macd(fast = 12, slow = 26, signal = 9): (value: number) => MacdValue {\n return holdGaps(macdOf(fast, slow, signal), { macd: Number.NaN, signal: Number.NaN, histogram: Number.NaN });\n}\n\nfunction macdOf(fast: number, slow: number, signal: number): (value: number) => MacdValue {\n const fastStep = ema(fast);\n const slowStep = ema(slow);\n const signalStep = ema(signal);\n return (value) => {\n const f = fastStep(value);\n const s = slowStep(value);\n const line = Number.isNaN(f) || Number.isNaN(s) ? Number.NaN : f - s;\n const sig = signalStep(line);\n return { macd: line, signal: sig, histogram: line - sig };\n };\n}\n\nexport interface BandsValue {\n readonly basis: number;\n readonly upper: number;\n readonly lower: number;\n}\n\n/** Bollinger Bands: a simple average and the lines `mult` standard deviations either side of it. */\nexport function bb(period = 20, mult = 2): (value: number) => BandsValue {\n return holdGaps(bandsOf(period, mult), { basis: Number.NaN, upper: Number.NaN, lower: Number.NaN });\n}\n\nfunction bandsOf(period: number, mult: number): (value: number) => BandsValue {\n const basisStep = sma(period);\n const devStep = stdev(period);\n return (value) => {\n const basis = basisStep(value);\n const dev = mult * devStep(value);\n return { basis, upper: basis + dev, lower: basis - dev };\n };\n}\n\n/** How far a value is from the one `bars` before it. */\nexport function change(bars = 1): Step {\n const n = whole(bars);\n const ring = new Ring(n);\n return (value) => {\n ring.push(num(value));\n return ring.at(0) - ring.at(n);\n };\n}\n\n/** Momentum: how far a value is from the one `period` bars before it. */\nexport function mom(period = 10): Step {\n return holdGaps(change(period), Number.NaN);\n}\n\n/** Rate of change in per cent from the value `period` bars before, as the built-in ROC: 0 from a value of 0. */\nexport function roc(period = 12): Step {\n return holdGaps(rocOf(period), Number.NaN);\n}\n\nfunction rocOf(period: number): Step {\n const n = whole(period);\n const ring = new Ring(n);\n return (value) => {\n ring.push(num(value));\n const now = ring.at(0);\n const before = ring.at(n);\n if (Number.isNaN(now) || Number.isNaN(before)) return Number.NaN;\n return before === 0 ? 0 : ((now - before) / before) * 100;\n };\n}\n","import { Ring } from '../Ring.js';\nimport { cell } from '../scope.js';\nimport { cleanPrices, num, whole, type BarPrices, type Step } from './common.js';\n\n/** A bar's true range: its range, stretched to the close before it; the first bar's is its own range. */\nexport function tr(): (bar: BarPrices) => number {\n const clean = cleanPrices();\n const state = cell({ prevClose: Number.NaN });\n return (raw) => {\n const bar = clean(raw);\n if (Number.isNaN(bar.close)) return Number.NaN;\n const range = bar.high - bar.low;\n const prev = state.prevClose;\n state.prevClose = bar.close;\n if (Number.isNaN(prev)) return range;\n return Math.max(range, Math.abs(bar.high - prev), Math.abs(bar.low - prev));\n };\n}\n\n/** Average True Range, as the built-in ATR: the simple average of the first `period` true ranges, then Wilder's smoothing. */\nexport function atr(period = 14): (bar: BarPrices) => number {\n const p = whole(period);\n const range = tr();\n const state = cell({ count: 0, value: 0 });\n return (bar) => {\n const r = range(bar);\n if (Number.isNaN(r)) return Number.NaN;\n if (state.count < p) {\n state.value += r;\n state.count++;\n if (state.count < p) return Number.NaN;\n state.value /= p;\n return state.value;\n }\n state.value = (state.value * (p - 1) + r) / p;\n return state.value;\n };\n}\n\nexport interface SupertrendValue {\n /** The line: under the bars while the trend is up, over them while it is down. */\n readonly value: number;\n /** 1 while the trend is up, -1 while it is down. */\n readonly trend: number;\n}\n\n/** Supertrend, as the built-in: bands `factor` ATRs from the bar's middle, each held until the close crosses it. */\nexport function supertrend(factor = 3, period = 10): (bar: BarPrices) => SupertrendValue {\n const p = whole(period);\n const range = atr(p);\n const state = cell({ prevClose: Number.NaN, upper: 0, lower: 0, line: 0 });\n const clean = cleanPrices();\n return (raw) => {\n const a = range(raw);\n const bar = clean(raw);\n const prevClose = Number.isNaN(state.prevClose) ? bar.close : state.prevClose;\n state.prevClose = bar.close;\n if (Number.isNaN(a)) return { value: Number.NaN, trend: Number.NaN };\n const middle = (bar.high + bar.low) / 2;\n const basicUpper = middle + factor * a;\n const basicLower = middle - factor * a;\n const upper = basicUpper < state.upper || prevClose > state.upper ? basicUpper : state.upper;\n const lower = basicLower > state.lower || prevClose < state.lower ? basicLower : state.lower;\n const line = state.line === state.upper\n ? (bar.close <= upper ? upper : lower)\n : (bar.close >= lower ? lower : upper);\n state.upper = upper;\n state.lower = lower;\n state.line = line;\n return { value: line, trend: line === lower ? 1 : -1 };\n };\n}\n\n/** The extreme of the last `period` values, by `better`; none while one is missing. */\nfunction extreme(period: number, better: (a: number, b: number) => boolean): Step {\n const p = whole(period);\n const ring = new Ring(p);\n return (value) => {\n ring.push(num(value));\n if (ring.given < p) return Number.NaN;\n let best = ring.at(0);\n for (let k = 0; k < p; k++) {\n const v = ring.at(k);\n if (Number.isNaN(v)) return Number.NaN;\n if (better(v, best)) best = v;\n }\n return best;\n };\n}\n\n/** The highest of the last `period` values. */\nexport function highest(period: number): Step {\n return extreme(period, (a, b) => a > b);\n}\n\n/** The lowest of the last `period` values. */\nexport function lowest(period: number): Step {\n return extreme(period, (a, b) => a < b);\n}\n","import { Ring } from '../Ring.js';\nimport { cell } from '../scope.js';\nimport { windowOf } from './averages.js';\nimport { cleanPrices, num, whole, type BarPrices, type Step } from './common.js';\n\n/*\n * Sums of where the price stands within its range, of volume, and of how\n * far back an extreme is. The ones a built-in indicator draws (Stochastic,\n * MFI, OBV, Parabolic SAR) take its steps, so the values are the chart's.\n */\n\n/** The raw stochastic %K: where `value` stands between the lowest low and the highest high of the last `period` bars, 0 to 100; 50 when they are one. */\nexport function stoch(period: number): (value: number, high: number, low: number) => number {\n const p = whole(period);\n const highs = new Ring(p);\n const lows = new Ring(p);\n return (value, high, low) => {\n highs.push(num(high));\n lows.push(num(low));\n const h = windowOf(highs, p);\n const l = windowOf(lows, p);\n const v = num(value);\n if (!h || !l || Number.isNaN(v)) return Number.NaN;\n const top = Math.max(...h);\n const bottom = Math.min(...l);\n return top === bottom ? 50 : ((v - bottom) / (top - bottom)) * 100;\n };\n}\n\n/**\n * The Money Flow Index of `value` (the typical price, as the built-in MFI\n * reads) and the volume: the share of the last `period` bars' money that\n * came on bars where it rose, 0 to 100; 100 when it never fell.\n */\nexport function mfi(period: number): (value: number, volume: number) => number {\n const p = whole(period);\n const prices = new Ring(p + 1);\n const volumes = new Ring(p + 1);\n return (value, volume) => {\n prices.push(num(value));\n volumes.push(num(volume));\n const tp = windowOf(prices, p + 1);\n const vol = windowOf(volumes, p + 1);\n if (!tp || !vol) return Number.NaN;\n let up = 0;\n let down = 0;\n for (let j = 1; j <= p; j++) {\n if (tp[j] > tp[j - 1]) up += tp[j] * vol[j];\n else if (tp[j] < tp[j - 1]) down += tp[j] * vol[j];\n }\n return down === 0 ? 100 : 100 - 100 / (1 + up / down);\n };\n}\n\n/** On-balance volume: each bar's volume added when the close rose, taken away when it fell; 0 on the first bar. */\nexport function obv(): (close: number, volume: number) => number {\n const state = cell({ value: 0, prev: Number.NaN });\n return (close, volume) => {\n const c = num(close);\n // A missing close gives none, and the next close is compared with the last one: the built-in reads a missing close as the one before.\n if (Number.isNaN(c)) return Number.NaN;\n const prev = state.prev;\n state.prev = c;\n if (Number.isNaN(prev)) return state.value;\n const vol = Number.isFinite(volume) ? volume : 0;\n if (c > prev) state.value += vol;\n else if (c < prev) state.value -= vol;\n return state.value;\n };\n}\n\n/**\n * Parabolic SAR, as the built-in: from the second bar, its trend first read\n * from the first two closes. The step starts at `start`, grows by\n * `increment` with each new extreme, up to `max`, and starts again at a turn.\n */\nexport function sar(start = 0.02, increment = 0.02, max = 0.2): (bar: BarPrices) => number {\n const clean = cleanPrices();\n const s = cell({ bars: 0, up: 0, af: 0, ep: 0, sar: 0, high1: 0, low1: 0, high2: 0, low2: 0, close1: 0 });\n return (raw) => {\n const bar = clean(raw);\n if (Number.isNaN(bar.close)) return Number.NaN;\n s.bars++;\n if (s.bars === 1) {\n s.high1 = bar.high;\n s.low1 = bar.low;\n s.close1 = bar.close;\n return Number.NaN;\n }\n if (s.bars === 2) {\n s.up = bar.close > s.close1 ? 1 : 0;\n s.af = start;\n s.ep = s.up ? s.high1 : s.low1;\n s.sar = s.up ? s.low1 : s.high1;\n }\n s.sar += s.af * (s.ep - s.sar);\n if (s.up) {\n s.sar = Math.min(s.sar, s.low1);\n if (s.bars > 2) s.sar = Math.min(s.sar, s.low2);\n if (bar.low < s.sar) {\n s.up = 0;\n s.sar = s.ep;\n s.ep = bar.low;\n s.af = start;\n } else if (bar.high > s.ep) {\n s.ep = bar.high;\n s.af = Math.min(s.af + increment, max);\n }\n } else {\n s.sar = Math.max(s.sar, s.high1);\n if (s.bars > 2) s.sar = Math.max(s.sar, s.high2);\n if (bar.high > s.sar) {\n s.up = 1;\n s.sar = s.ep;\n s.ep = bar.high;\n s.af = start;\n } else if (bar.low < s.ep) {\n s.ep = bar.low;\n s.af = Math.min(s.af + increment, max);\n }\n }\n s.high2 = s.high1;\n s.low2 = s.low1;\n s.high1 = bar.high;\n s.low1 = bar.low;\n return s.sar;\n };\n}\n\n/** How many bars back the extreme of the last `period` values is, as an offset at or under 0; the newest of equal ones. */\nfunction extremeBars(period: number, beats: (a: number, b: number) => boolean): Step {\n const p = whole(period);\n const ring = new Ring(p);\n return (value) => {\n ring.push(num(value));\n const values = windowOf(ring, p);\n if (!values) return Number.NaN;\n let best = p - 1;\n for (let j = p - 2; j >= 0; j--) if (beats(values[j], values[best])) best = j;\n return best - (p - 1);\n };\n}\n\n/** How many bars back the highest of the last `period` values is, as an offset at or under 0. */\nexport function highestbars(period: number): Step {\n return extremeBars(period, (a, b) => a > b);\n}\n\n/** How many bars back the lowest of the last `period` values is, as an offset at or under 0. */\nexport function lowestbars(period: number): Step {\n return extremeBars(period, (a, b) => a < b);\n}\n\n/** Whether a value is beyond every one of the `period` before it. */\nfunction beyond(period: number, beats: (a: number, b: number) => boolean): (value: number) => boolean {\n const p = whole(period);\n const ring = new Ring(p + 1);\n return (value) => {\n ring.push(num(value));\n const values = windowOf(ring, p + 1);\n if (!values) return false;\n for (let k = 0; k < p; k++) if (!beats(values[p], values[k])) return false;\n return true;\n };\n}\n\n/** Whether the value is over every one of the `period` before it. */\nexport function rising(period: number): (value: number) => boolean {\n return beyond(period, (a, b) => a > b);\n}\n\n/** Whether the value is under every one of the `period` before it. */\nexport function falling(period: number): (value: number) => boolean {\n return beyond(period, (a, b) => a < b);\n}\n","import { Ring } from '../Ring.js';\nimport { cell } from '../scope.js';\nimport { windowOf } from './averages.js';\nimport { num, whole, type Step } from './common.js';\n\n/*\n * Sums over a window of the last `period` values. As the simple average, a\n * window with a missing value (NaN) in it gives none: each needs `period`\n * numbers in a row. The ones a built-in indicator draws (ALMA, LSMA) take\n * its steps, so the values are the chart's.\n */\n\n/** A sum over each whole window of `p` values. */\nfunction overWindow(period: number, of: (values: number[], p: number) => number): Step {\n const p = whole(period);\n const ring = new Ring(p);\n return (value) => {\n ring.push(num(value));\n const values = windowOf(ring, p);\n return values ? of(values, p) : Number.NaN;\n };\n}\n\n/** The longest window of the sums the built-in indicators cap (ALMA, LSMA). */\nconst MAX_WINDOW = 5000;\n\nconst total = (values: number[]) => values.reduce((a, b) => a + b, 0);\nconst ascending = (values: number[]) => [...values].sort((a, b) => a - b);\n\n/** The sum of the last `period` values. */\nexport function sum(period: number): Step {\n return overWindow(period, total);\n}\n\n/** The running total of every value so far; a missing one is passed over. None before the first number. */\nexport function cum(): Step {\n const state = cell({ total: 0, seen: 0 });\n return (value) => {\n const v = num(value);\n if (!Number.isNaN(v)) {\n state.total += v;\n state.seen = 1;\n }\n return state.seen ? state.total : Number.NaN;\n };\n}\n\n/** The middle of the last `period` values; of an even count, the mean of the two in the middle. */\nexport function median(period: number): Step {\n return overWindow(period, (values, p) => {\n const s = ascending(values);\n const mid = Math.floor(p / 2);\n return p % 2 === 1 ? s[mid] : (s[mid - 1] + s[mid]) / 2;\n });\n}\n\n/** A percentage within 0 and 100, or NaN for one that is no number. */\nfunction percent(percentage: number): number {\n return Number.isFinite(percentage) ? Math.min(100, Math.max(0, percentage)) : Number.NaN;\n}\n\n/** The value `percentage` of the way up the last `period` values, by the nearest rank: one of the values itself. */\nexport function percentileNearestRank(period: number, percentage: number): Step {\n const pct = percent(percentage);\n return overWindow(period, (values, p) => {\n if (Number.isNaN(pct)) return Number.NaN;\n // The rank as a whole number before dividing: 7 % of 100 is rank 7, where 0.07 * 100 is a hair over 7.\n const rank = Math.max(1, Math.ceil(Math.round(pct * p * 1e6) / 1e8));\n return ascending(values)[rank - 1];\n });\n}\n\n/** The value `percentage` of the way up the last `period` values, between the two values either side of it. */\nexport function percentileLinearInterpolation(period: number, percentage: number): Step {\n const pct = percent(percentage);\n return overWindow(period, (values, p) => {\n if (Number.isNaN(pct)) return Number.NaN;\n const s = ascending(values);\n const x = (pct * (p - 1)) / 100;\n const below = Math.floor(x);\n return s[below] + (s[Math.ceil(x)] - s[below]) * (x - below);\n });\n}\n\n/** How many of the `period` values before this one are at or under it, as a percentage. */\nexport function percentrank(period: number): Step {\n const p = whole(period);\n const ring = new Ring(p + 1);\n return (value) => {\n ring.push(num(value));\n const values = windowOf(ring, p + 1);\n if (!values) return Number.NaN;\n const now = values[p];\n let under = 0;\n for (let k = 0; k < p; k++) if (values[k] <= now) under++;\n return (under / p) * 100;\n };\n}\n\n/** The mean distance of the last `period` values from their mean. */\nexport function dev(period: number): Step {\n return overWindow(period, (values, p) => {\n const mean = total(values) / p;\n return total(values.map((v) => Math.abs(v - mean))) / p;\n });\n}\n\n/** The variance of the whole population of the last `period` values: `ta.stdev` squared, worked out the same way. */\nexport function variance(period: number): Step {\n return overWindow(period, (values, p) => {\n let sum = 0;\n let sumSq = 0;\n for (const v of values) {\n sum += v;\n sumSq += v * v;\n }\n const mean = sum / p;\n return Math.max(0, sumSq / p - mean * mean);\n });\n}\n\n/** How closely two values move together over the last `period` bars, from -1 to 1; none while either stays flat. */\nexport function correlation(period: number): (a: number, b: number) => number {\n const p = whole(period);\n const as = new Ring(p);\n const bs = new Ring(p);\n return (a, b) => {\n as.push(num(a));\n bs.push(num(b));\n const x = windowOf(as, p);\n const y = windowOf(bs, p);\n if (!x || !y) return Number.NaN;\n const mx = total(x) / p;\n const my = total(y) / p;\n let xy = 0;\n let xx = 0;\n let yy = 0;\n for (let k = 0; k < p; k++) {\n xy += (x[k] - mx) * (y[k] - my);\n xx += (x[k] - mx) ** 2;\n yy += (y[k] - my) ** 2;\n }\n return xx > 0 && yy > 0 ? xy / Math.sqrt(xx * yy) : Number.NaN;\n };\n}\n\n/** The least-squares line through the last `period` values (2 to 5000), read at the newest (or `offset` bars before it), as the built-in LSMA. */\nexport function linreg(period: number, offset = 0): Step {\n const back = Math.max(-1000, Math.round(Number.isFinite(offset) ? offset : 0));\n return overWindow(Math.min(MAX_WINDOW, Math.max(2, whole(period))), (values, p) => {\n const sx = (p * (p - 1)) / 2;\n const sxx = ((p - 1) * p * (2 * p - 1)) / 6;\n const denom = p * sxx - sx * sx;\n let sy = 0;\n let sxy = 0;\n for (let x = 0; x < p; x++) {\n sy += values[x];\n sxy += x * values[x];\n }\n const slope = (p * sxy - sx * sy) / denom;\n return (sy - slope * sx) / p + slope * (p - 1 - back);\n });\n}\n\n/** The Arnaud Legoux moving average, as the built-in ALMA: weights in a bell `offset` of the way along the window, `sigma` setting its width. */\nexport function alma(period: number, offset = 0.85, sigma = 6): Step {\n const p = Math.min(MAX_WINDOW, whole(period));\n // A setting that is no number is the default, as the built-in reads it.\n const m = Math.min(1, Math.max(0, Number.isFinite(offset) ? offset : 0.85)) * (p - 1);\n const s = p / Math.max(0.5, Number.isFinite(sigma) ? sigma : 6);\n // Weight j applies to the j-th oldest value of the window.\n const weights = Array.from({ length: p }, (_, j) => Math.exp(-((j - m) ** 2) / (2 * s * s)));\n const norm = total(weights);\n return overWindow(p, (values) => {\n let sum = 0;\n for (let j = 0; j < p; j++) sum += weights[j] * values[j];\n return sum / norm;\n });\n}\n\n/** The symmetrically weighted average of the last four values: weights 1, 2, 2, 1. */\nexport function swma(): Step {\n return overWindow(4, (v) => (v[0] + 2 * v[1] + 2 * v[2] + v[3]) / 6);\n}\n","import { ema, hma, rma, sma, stdev, vwma, wma } from './averages.js';\nimport { barssince, cross, crossover, crossunder, pivothigh, pivotlow, valuewhen } from './events.js';\nimport { bb, change, macd, mom, roc, rsi } from './oscillators.js';\nimport { atr, highest, lowest, supertrend, tr } from './ranges.js';\nimport { falling, highestbars, lowestbars, mfi, obv, rising, sar, stoch } from './moves.js';\nimport {\n alma,\n correlation,\n cum,\n dev,\n linreg,\n median,\n percentileLinearInterpolation,\n percentileNearestRank,\n percentrank,\n sum,\n swma,\n variance,\n} from './statistics.js';\n\nexport type { BandsValue, MacdValue } from './oscillators.js';\nexport type { SupertrendValue } from './ranges.js';\nexport type { BarPrices, Step } from './common.js';\n\n/**\n * The sums a script is made of, each run a bar at a time. Make one in the\n * script's setup (`const fast = ta.ema(9)`), then give it a value on each\n * bar (`fast(bar.close)`): it keeps its own state, so two calls of\n * `ta.ema(9)` are two averages. Their values are the chart's own built-in\n * indicators' (`@tradecanvas/core`), a missing value (NaN) handled as there.\n */\nexport const ta = {\n sma,\n ema,\n rma,\n wma,\n vwma,\n hma,\n stdev,\n bb,\n rsi,\n macd,\n change,\n mom,\n roc,\n tr,\n atr,\n supertrend,\n highest,\n lowest,\n crossover,\n crossunder,\n cross,\n pivothigh,\n pivotlow,\n barssince,\n valuewhen,\n sum,\n cum,\n median,\n percentileNearestRank,\n percentileLinearInterpolation,\n percentrank,\n dev,\n variance,\n correlation,\n linreg,\n alma,\n swma,\n stoch,\n mfi,\n obv,\n sar,\n highestbars,\n lowestbars,\n rising,\n falling,\n};\n\nexport type ScriptTa = typeof ta;\n","import type { IndicatorValue } from '@tradecanvas/commons';\nimport type { BarColors, ScriptOutput } from './outputs.js';\n\n// How a script's output reads as the chart's values: one point a bar, under keys.\n\n/** What a mark, a background, is stored as on its bars: any number marks it. */\nconst MARKED = 1;\n\nexport const plotKey = (i: number) => `p${i}`;\nexport const shapeKey = (i: number) => `s${i}`;\nexport const backgroundKey = (i: number) => `bg${i}`;\nexport const barColorKey = (i: number) => `bc${i}`;\n/** The field that holds a bar's colour, by its place in the output's palette. */\nexport const colorKey = (key: string) => `${key}c`;\nexport const fillColorKey = (i: number) => `f${i}c`;\nexport const conditionKey = (i: number) => `a${i}`;\n\n/** Set `key` on `point` to bar `i`'s palette place, when the bar was given a colour. */\nfunction withColor(point: IndicatorValue, key: string, colors: BarColors, i: number): void {\n const color = colors[i];\n if (color > 0) point[key] = color - 1;\n}\n\n/** Bar `i`'s values under their keys, or null when it has none. */\nexport function pointAt(output: ScriptOutput, i: number): IndicatorValue | null {\n const point: IndicatorValue = {};\n output.plots.forEach((plot, k) => {\n const value = plot.values[i];\n if (!Number.isFinite(value)) return;\n point[plotKey(k)] = value;\n withColor(point, colorKey(plotKey(k)), plot.colors, i);\n });\n output.shapes.forEach((shape, k) => {\n if (shape.on[i] === 1) point[shapeKey(k)] = MARKED;\n });\n output.backgrounds.forEach((background, k) => {\n if (background.colors[i] === 0) return;\n point[backgroundKey(k)] = MARKED;\n withColor(point, colorKey(backgroundKey(k)), background.colors, i);\n });\n output.fills.forEach((fill, k) => withColor(point, fillColorKey(k), fill.colors, i));\n output.barColors.forEach((colors, k) => {\n if (colors[i] === 0) return;\n point[barColorKey(k)] = MARKED;\n withColor(point, colorKey(barColorKey(k)), colors, i);\n });\n // A condition is 1 or 0 on every bar: an alert sees it turn true.\n output.alertConditions.forEach((condition, k) => {\n point[conditionKey(k)] = condition.on[i] === 1 ? 1 : 0;\n });\n for (const _ in point) return point;\n return null;\n}\n\n","import type {\n DataSeries,\n IndicatorConfig,\n IndicatorDescriptor,\n IndicatorFill,\n IndicatorLevelLook,\n IndicatorMarkerPosition,\n IndicatorOutput,\n IndicatorPlot,\n IndicatorPlugin,\n TimeFrame,\n} from '@tradecanvas/commons';\nimport { fadeBy } from '@tradecanvas/commons';\nimport { IndicatorBase, IndicatorValueMap } from '@tradecanvas/core';\nimport type { Script, ScriptInputs, ShapePosition } from './defineScript.js';\nimport type { LevelDeclaration, ScriptDeclarations } from './outputs.js';\nimport { limitsOf, type ScriptLimits } from './limits.js';\nimport { ScriptRun, type ScriptRunOptions } from './ScriptRun.js';\nimport { backgroundKey, barColorKey, colorKey, conditionKey, fillColorKey, plotKey, pointAt, shapeKey } from './points.js';\n\n/** The colours of plots that name none, in order. */\nconst FALLBACK_COLORS = ['#2962ff', '#ff6d00', '#00bfa5', '#d500f9', '#ffd600', '#ef5350', '#26a69a', '#8d6e63'];\n\n/** How faint a fill that names no colour is: its first plot's colour at this strength. */\nconst FILL_STRENGTH = 0.15;\n\n/**\n * Where a script's mark goes on the chart: over and under a bar on the\n * prices; in a pane of its own, where a bar has no high or low on the\n * scale, the top and the bottom of the pane.\n */\nfunction markPosition(position: ShapePosition, overlay: boolean): IndicatorMarkerPosition {\n if (overlay || position === 'top' || position === 'bottom') return position;\n return position === 'aboveBar' ? 'top' : 'bottom';\n}\n\n/** A run's options for an instance: its limits, and the exchange's clock its days are counted on. */\nexport function runOptionsOf(config: IndicatorConfig, limits?: ScriptLimits): ScriptRunOptions {\n return {\n ...(limits ? { limits } : {}),\n ...(config.exchangeTimeZone ? { exchangeTimeZone: config.exchangeTimeZone } : {}),\n ...(config.sessionStart !== undefined ? { sessionStart: config.sessionStart } : {}),\n ...(config.interval !== undefined ? { interval: config.interval as TimeFrame } : {}),\n };\n}\n\n/** The inputs a run was made with, to tell whether a config asks for others. */\nexport function paramsKey(params: Readonly<Record<string, unknown>>): string {\n return JSON.stringify(Object.keys(params).sort().map((name) => [name, params[name]]));\n}\n\n/** What the chart draws of a script: its plots, marks, backgrounds and fills, and the colours they start in. */\nfunction drawingOf(declared: ScriptDeclarations): Pick<IndicatorDescriptor, 'plots' | 'fills'> & { colors: string[] } {\n const colors: string[] = [];\n let fallback = 0;\n const colorIndex = (color: string | undefined) => {\n colors.push(color ?? FALLBACK_COLORS[fallback++ % FALLBACK_COLORS.length]);\n return colors.length - 1;\n };\n const lines: IndicatorPlot[] = declared.plots.map((plot, i) => ({\n key: plotKey(i),\n title: plot.title,\n color: colorIndex(plot.color),\n paletteBy: colorKey(plotKey(i)),\n ...(plot.kind !== 'line' ? { kind: plot.kind } : {}),\n ...(plot.width !== undefined ? { width: plot.width } : {}),\n }));\n const marks: IndicatorPlot[] = declared.shapes.map((shape, i) => ({\n key: shapeKey(i),\n title: shape.title,\n color: colorIndex(shape.color),\n kind: 'markers',\n shape: shape.shape,\n position: markPosition(shape.position, declared.overlay),\n }));\n // Drawn behind everything in a pass of their own, so last in the list: the lines keep their places for widths. A bar without a colour has no background.\n const backgrounds: IndicatorPlot[] = declared.backgrounds.map((background, i) => ({\n key: backgroundKey(i),\n title: background.title,\n color: colorIndex(undefined),\n kind: 'background',\n paletteBy: colorKey(backgroundKey(i)),\n // Its colours carry their own strength, as a script gives them.\n opacity: 1,\n }));\n const fills: IndicatorFill[] = declared.fills.map((fill, i) => {\n const first = colors[lines[fill.between[0]].color];\n return {\n between: [plotKey(fill.between[0]), plotKey(fill.between[1])],\n color: colorIndex(fill.color ?? fadeBy(first, FILL_STRENGTH)),\n paletteBy: fillColorKey(i),\n // Its colours carry their own strength.\n opacity: 1,\n };\n });\n // Bars painted: a bar without a colour keeps the chart's own.\n const barColors: IndicatorPlot[] = Array.from({ length: declared.barColors }, (_, i) => ({\n key: barColorKey(i),\n title: 'Bars',\n color: colorIndex(undefined),\n kind: 'barColor',\n paletteBy: colorKey(barColorKey(i)),\n }));\n return { plots: [...lines, ...marks, ...backgrounds, ...barColors], fills, colors };\n}\n\n/** The indicator a script is to the chart: its id, inputs, plots, fills and levels, known from its setup. */\nexport function describeScript(script: Script<ScriptInputs>): IndicatorDescriptor {\n const run = new ScriptRun(script);\n const declared = run.declarations;\n const { plots, fills, colors } = drawingOf(declared);\n const inputs = script.inputs ?? {};\n const names = Object.keys(inputs);\n return {\n id: script.id,\n name: script.name,\n placement: declared.overlay ? 'overlay' : 'panel',\n defaultConfig: Object.fromEntries(names.map((name) => [name, inputs[name].default])),\n plots,\n ...(fills && fills.length > 0 ? { fills } : {}),\n ...(script.shortName !== undefined ? { shortName: script.shortName } : {}),\n ...(declared.levels.length > 0 ? { levels: declared.levels.map((level) => level.price) } : {}),\n ...levelLooksOf(declared.levels),\n ...(names.length > 0 ? { inputs: Object.fromEntries(names.map((name) => { const { default: _start, ...spec } = inputs[name]; return [name, spec]; })) } : {}),\n ...(colors.length > 0 ? { defaultStyle: { colors } } : {}),\n ...(declared.alertConditions.length > 0\n ? { alertConditions: declared.alertConditions.map((condition, i) => ({ key: conditionKey(i), ...condition })) }\n : {}),\n // A higher interval of days is cut on the exchange's clock: a new zone or day start runs it again.\n readsExchangeTimeZone: true,\n ...(run.readsInterval ? { readsInterval: true } : {}),\n };\n}\n\nclass ScriptIndicator extends IndicatorBase {\n readonly descriptor: IndicatorDescriptor;\n private readonly runs = new WeakMap<IndicatorOutput, { run: ScriptRun; params: string; interval?: string }>();\n\n constructor(\n private readonly script: Script<ScriptInputs>,\n private readonly options: ScriptIndicatorOptions = {},\n ) {\n super();\n this.descriptor = describeScript(script);\n }\n\n calculate(data: DataSeries, config: IndicatorConfig): IndicatorOutput {\n // Days counted on the exchange's clock, from its trading day's start: a daily interval's bars as the chart's.\n const run = new ScriptRun(this.script, config.params, runOptionsOf(config, this.options.limits));\n run.load(data);\n const output: IndicatorOutput = { values: new IndicatorValueMap(), series: new Array(data.length).fill(null), meta: {} };\n this.writeFrom(output, data, run, 0);\n this.runs.set(output, { run, params: paramsKey(config.params), interval: config.interval });\n return output;\n }\n\n /** Runs the live bar again on a tick, and new bars as they come; older bars changed, or other inputs, ask for a full calculate. */\n update(data: DataSeries, config: IndicatorConfig, prev: IndicatorOutput, from: number): IndicatorOutput | null {\n const entry = this.runs.get(prev);\n // A run was made on an interval: another is a run of its own.\n const moved = this.descriptor.readsInterval === true && entry?.interval !== config.interval;\n if (!entry || moved || entry.params !== paramsKey(config.params) || !this.canResume(data, prev, from)) return null;\n const { run } = entry;\n if (from < run.length - 1 || data.length < run.length) return null;\n for (let i = from; i < data.length; i++) {\n if (i === run.length - 1) run.tick(data[i]);\n else run.next(data[i]);\n }\n prev.series!.length = data.length;\n // The live bar before a new one ran again as it closed.\n this.writeFrom(prev, data, run, Math.max(0, from - 1));\n return prev;\n }\n\n /** The bar before a new one runs again as it closes, and may read otherwise then (`bar.live`). */\n revisesBefore(): number {\n return 1;\n }\n\n private writeFrom(out: IndicatorOutput, data: DataSeries, run: ScriptRun, from: number): void {\n const output = run.output;\n // The colours its bars named, which no style lists; they only grow.\n out.palette = output.palette;\n // Its labels, lines and boxes, drawn by the chart over its plots.\n out.drawings = output.drawings;\n // Where it stopped and why: its lines end there, and an app can show it.\n out.meta = { ...out.meta, errors: output.errors };\n for (let i = from; i < data.length; i++) this.writePoint(out, data, i, pointAt(output, i));\n }\n}\n\n/** The hlines given a colour, a dash or a name, as the pane's level looks. */\nfunction levelLooksOf(levels: readonly LevelDeclaration[]): { levelLooks?: IndicatorLevelLook[] } {\n const looks = levels\n .filter((level) => level.color !== undefined || level.lineStyle !== undefined || level.title !== undefined)\n .map(({ price, color, lineStyle, title }) => ({\n price,\n ...(color !== undefined ? { color } : {}),\n ...(lineStyle !== undefined ? { lineStyle } : {}),\n ...(title !== undefined ? { title } : {}),\n }));\n return looks.length > 0 ? { levelLooks: looks } : {};\n}\n\n/** How a script is run as an indicator. */\nexport interface ScriptIndicatorOptions {\n /** How far each run may go: loop steps a bar, numbers a list, ms a run. */\n limits?: ScriptLimits;\n}\n\n/**\n * A script as an indicator the chart draws: register it\n * (`chart.registerIndicator(scriptIndicator(script))`) and add it by its id.\n * Its plots are its lines under the keys `p0`, `p1`…, its marks `s0`, `s1`…,\n * its backgrounds `bg0`…, its levels the pane's. A colour a bar is an index\n * into the output's `palette` (`p0c`, `bg0c`, `f0c` for a fill). A tick\n * runs only the live bar again.\n */\nexport function scriptIndicator(script: Script<ScriptInputs>, options: ScriptIndicatorOptions = {}): IndicatorPlugin {\n // A bad limit is refused here, as the indicator is made, not on its first run.\n if (options.limits) limitsOf(options.limits);\n return new ScriptIndicator(script, options);\n}\n","import type {\n DataSeries,\n IndicatorConfig,\n IndicatorDescriptor,\n IndicatorOutput,\n IndicatorPlugin,\n IndicatorPluginHost,\n IndicatorValue,\n} from '@tradecanvas/commons';\nimport { IndicatorBase, IndicatorValueMap } from '@tradecanvas/core';\nimport type { Script, ScriptInputs } from '../defineScript.js';\nimport { limitsOf, type ScriptLimits } from '../limits.js';\nimport type { ScriptError } from '../outputs.js';\nimport { describeScript, paramsKey, runOptionsOf } from '../scriptIndicator.js';\nimport type { ScriptWorkerRequest, ScriptWorkerResponse } from './messages.js';\n\n/** How long a request may go unanswered by default, in ms. */\nconst DEFAULT_TIMEOUT_MS = 5000;\n\n/** What the page's side needs of a worker: `Worker` is one. */\nexport interface ScriptWorkerLike {\n postMessage(message: unknown): void;\n addEventListener(type: 'message', listener: (event: MessageEvent) => void): void;\n terminate(): void;\n}\n\nexport interface ScriptWorkerOptions {\n /**\n * Start the worker that serves the script (its module calls\n * `serveScripts`). Called when first needed, and again after a worker\n * was stopped.\n */\n spawn: () => ScriptWorkerLike;\n /**\n * How long one request may go unanswered, in ms, the first load of the\n * bars among them, before the worker is stopped and the script it hung\n * on with it: a bar that never returns is stopped this way. Default 5000.\n */\n timeoutMs?: number;\n /** How far each run may go in the worker: loop steps a bar, numbers a list, ms a run. */\n limits?: ScriptLimits;\n}\n\n/** One instance's run in the worker, and the output the chart draws of it. */\ninterface Entry {\n readonly run: number;\n readonly config: IndicatorConfig;\n /** The inputs and the clock it was loaded with. */\n readonly key: string;\n /** The bars it was loaded with, by identity: other bars load it again. */\n readonly bars: DataSeries;\n /** What the chart draws: the instance's last output, kept while it loads again, till the first answer. */\n readonly output: IndicatorOutput;\n /** The bars the worker's run holds once what was sent is done. */\n length: number;\n /** The bars as last sent; empty: load again at the next computation. */\n sent: string;\n /** Stopped: by a worker that hung on it, or one that could not run it. Loaded again only for other inputs or bars. */\n stopped: boolean;\n}\n\n/** How the bars stand for what was sent: how many, and the last one. */\nfunction sentOf(data: DataSeries): string {\n const last = data[data.length - 1];\n return last ? `${data.length}|${last.time}|${last.open}|${last.high}|${last.low}|${last.close}|${last.volume ?? 0}` : '0';\n}\n\n/** What an instance is loaded with besides the bars: its inputs and the exchange's clock. */\nfunction keyOf(config: IndicatorConfig, readsInterval: boolean): string {\n return `${paramsKey(config.params)}|${config.exchangeTimeZone ?? ''}|${config.sessionStart ?? ''}|${readsInterval ? config.interval ?? '' : ''}`;\n}\n\nfunction emptyOutput(length: number): IndicatorOutput {\n return { values: new IndicatorValueMap(), series: new Array(length).fill(null), meta: { errors: [] } };\n}\n\n/** `output` cut or padded to `length` bars: drawn as it was while the bars load again. */\nfunction resized(output: IndicatorOutput, length: number): IndicatorOutput {\n const series = output.series!;\n if (series.length > length) series.length = length;\n while (series.length < length) series.push(null);\n return output;\n}\n\nclass ScriptWorkerIndicator extends IndicatorBase {\n readonly descriptor: IndicatorDescriptor;\n private worker: ScriptWorkerLike | null = null;\n private readonly hosts = new Set<IndicatorPluginHost>();\n /** Each instance's run, by its config: a config is one instance on one chart. */\n private readonly entries = new WeakMap<IndicatorConfig, Entry>();\n /** The runs in the worker, by number. */\n private readonly runs = new Map<number, Entry>();\n /** The run of each request not yet answered, in the order sent: the worker answers in that order. */\n private pending: number[] = [];\n /** The instances whose answers came this task: the chart is asked once for each. */\n private readonly due = new Set<Entry>();\n private nextRun = 1;\n private nextSeq = 1;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private readonly timeoutMs: number;\n\n constructor(\n private readonly script: Script<ScriptInputs>,\n private readonly options: ScriptWorkerOptions,\n ) {\n super();\n this.descriptor = describeScript(script);\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n }\n\n connect(host: IndicatorPluginHost): () => void {\n this.hosts.add(host);\n return () => {\n this.hosts.delete(host);\n };\n }\n\n /** The instance is gone: its run goes, and the worker once it runs nothing. */\n release(config: IndicatorConfig): void {\n const entry = this.entries.get(config);\n if (!entry) return;\n this.entries.delete(config);\n this.drop(entry);\n if (this.runs.size === 0) this.stopWorker();\n }\n\n /**\n * The worker's output for these bars when it has come, or is coming (a\n * tick sent meanwhile); otherwise the bars are sent to be run, and what\n * was drawn stays till the worker answers.\n */\n calculate(data: DataSeries, config: IndicatorConfig): IndicatorOutput {\n const entry = this.entries.get(config);\n const current = entry && entry.key === this.keyOf(config) && entry.bars === data;\n if (current && (entry.stopped || (entry.sent !== '' && entry.sent === sentOf(data)))) return entry.output;\n return this.load(data, config, entry).output;\n }\n\n /** A tick, or new bars, sent to the worker one bar each; the output stays as it is till the answer comes. */\n update(data: DataSeries, config: IndicatorConfig, prev: IndicatorOutput, from: number): IndicatorOutput | null {\n const entry = this.entries.get(config);\n if (!entry || entry.output !== prev || entry.stopped || entry.key !== this.keyOf(config) || entry.bars !== data || entry.sent === '') return null;\n if (from < entry.length - 1 || from > entry.length || data.length < entry.length) {\n // An older bar changed, or bars went missing: the full computation that follows loads them again.\n entry.sent = '';\n return null;\n }\n for (let i = from; i < data.length; i++) {\n const type = i === entry.length - 1 ? 'tick' : 'next';\n this.send(entry, { type, run: entry.run, seq: this.nextSeq++, bar: data[i] });\n if (type === 'next') entry.length = i + 1;\n }\n resized(prev, data.length);\n entry.sent = sentOf(data);\n return prev;\n }\n\n /** What a run was made for: another loads the bars again. */\n private keyOf(config: IndicatorConfig): string {\n return keyOf(config, this.descriptor.readsInterval === true);\n }\n\n private load(data: DataSeries, config: IndicatorConfig, before: Entry | undefined): Entry {\n if (before) this.drop(before);\n const entry: Entry = {\n run: this.nextRun++,\n config,\n key: this.keyOf(config),\n bars: data,\n output: before ? resized(before.output, data.length) : emptyOutput(data.length),\n length: data.length,\n sent: sentOf(data),\n stopped: false,\n };\n this.entries.set(config, entry);\n this.runs.set(entry.run, entry);\n this.send(entry, {\n type: 'load',\n run: entry.run,\n seq: this.nextSeq++,\n script: this.script.id,\n params: { ...config.params },\n options: runOptionsOf(config, this.options.limits),\n bars: data.map((bar) => ({ ...bar })),\n });\n return entry;\n }\n\n /** Forget a run here and in the worker. */\n private drop(entry: Entry): void {\n if (!this.runs.delete(entry.run)) return;\n this.worker?.postMessage({ type: 'drop', run: entry.run } satisfies ScriptWorkerRequest);\n }\n\n private send(entry: Entry, request: ScriptWorkerRequest): void {\n this.pending.push(entry.run);\n this.ensureWorker().postMessage(request);\n if (this.pending.length === 1) this.armTimer();\n }\n\n private ensureWorker(): ScriptWorkerLike {\n if (this.worker) return this.worker;\n const worker = this.options.spawn();\n worker.addEventListener('message', (event) => {\n if (this.worker === worker) this.receive(event.data as ScriptWorkerResponse);\n });\n this.worker = worker;\n return worker;\n }\n\n private stopWorker(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.pending = [];\n this.worker?.terminate();\n this.worker = null;\n }\n\n /** The oldest request has `timeoutMs` from now to be answered. */\n private armTimer(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = setTimeout(() => this.timedOut(), this.timeoutMs);\n }\n\n private receive(response: ScriptWorkerResponse): void {\n // Answered in the order sent: the oldest request is done, and the next has its own time.\n this.pending.shift();\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n if (this.pending.length > 0) this.armTimer();\n const entry = this.runs.get(response.run);\n if (!entry) return;\n if (response.type === 'patch') this.apply(entry, response.from, response.points, response.palette, response.drawings, response.errors);\n else this.stop(entry, { bar: Math.max(0, entry.length - 1), message: response.message });\n this.recompute(entry);\n }\n\n private apply(entry: Entry, from: number, points: (IndicatorValue | null)[], palette: string[], drawings: IndicatorOutput['drawings'], errors: ScriptError[]): void {\n const out = entry.output;\n const series = out.series!;\n if (from === 0) {\n // A load's answer: what was drawn while it ran goes.\n out.values.clear();\n series.fill(null);\n }\n for (let k = 0; k < points.length; k++) {\n const i = from + k;\n // A point of a bar the chart no longer holds is passed over: the next load brings the bars as they are.\n if (i >= entry.bars.length) break;\n while (series.length <= i) series.push(null);\n this.writePoint(out, entry.bars, i, points[k]);\n }\n out.palette = palette;\n out.drawings = drawings ?? [];\n out.meta = { ...out.meta, errors };\n }\n\n /**\n * The worker did not answer in time. It answers in order, so it hung on\n * the oldest request: that run is stopped, the worker with it, and the\n * other runs load again in a new one.\n */\n private timedOut(): void {\n this.timer = null;\n const hung = this.pending[0];\n this.stopWorker();\n const runs = [...this.runs.values()];\n this.runs.clear();\n for (const entry of runs) {\n if (entry.run === hung) {\n this.stop(entry, { bar: Math.max(0, entry.length - 1), message: `the script did not answer within ${this.timeoutMs} ms, and was stopped`, limit: 'time' });\n } else {\n entry.sent = '';\n }\n this.recompute(entry);\n }\n }\n\n private stop(entry: Entry, error: ScriptError): void {\n entry.stopped = true;\n this.runs.delete(entry.run);\n entry.output.meta = { ...entry.output.meta, errors: [error] };\n }\n\n /** Ask the chart to compute the instance again, once for all the answers that came this task. */\n private recompute(entry: Entry): void {\n if (this.due.size === 0) queueMicrotask(() => this.flush());\n this.due.add(entry);\n }\n\n private flush(): void {\n const due = [...this.due];\n this.due.clear();\n for (const entry of due) {\n // An instance let go, or loaded again since, is passed over.\n if (this.entries.get(entry.config) !== entry) continue;\n for (const host of this.hosts) host.recompute(entry.config);\n }\n }\n}\n\n/**\n * A script as an indicator run in a worker: the page sends it the bars,\n * one bar each on a tick, and draws what it answers. A worker that does\n * not answer within `timeoutMs` is stopped, so a script that never returns\n * cannot hang the page. The worker's module serves the same script\n * (`serveScripts`); the setup runs here too, once, to know what it draws.\n *\n * ```ts\n * chart.registerIndicator(scriptWorkerIndicator(emaCross, {\n * spawn: () => new Worker(new URL('./scripts.worker.ts', import.meta.url), { type: 'module' }),\n * }))\n * ```\n */\nexport function scriptWorkerIndicator(script: Script<ScriptInputs>, options: ScriptWorkerOptions): IndicatorPlugin {\n // A bad limit is refused here, as the indicator is made.\n if (options.limits) limitsOf(options.limits);\n if (options.timeoutMs !== undefined && !(options.timeoutMs > 0)) throw new RangeError(`scriptWorkerIndicator: timeoutMs must be a positive number, not ${options.timeoutMs}`);\n return new ScriptWorkerIndicator(script, options);\n}\n","import type { IndicatorValue } from '@tradecanvas/commons';\nimport type { Script, ScriptInputs } from '../defineScript.js';\nimport { pointAt } from '../points.js';\nimport { ScriptRun } from '../ScriptRun.js';\nimport type { PatchResponse, ScriptWorkerRequest, ScriptWorkerResponse } from './messages.js';\n\n/** How the worker answers. */\nexport type ScriptWorkerPost = (message: ScriptWorkerResponse) => void;\n\n/** What a worker's global scope gives `serveScripts`: its messages in, and a way to answer. */\nexport interface ScriptWorkerScope {\n addEventListener(type: 'message', listener: (event: MessageEvent) => void): void;\n postMessage(message: unknown): void;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** What changed in `run` from bar `from`: the points as the chart reads them, and what the run holds now. */\nfunction patchOf(id: number, seq: number, run: ScriptRun, from: number): PatchResponse {\n const output = run.output;\n const points: (IndicatorValue | null)[] = [];\n for (let i = from; i < output.length; i++) points.push(pointAt(output, i));\n return {\n type: 'patch',\n run: id,\n seq,\n from,\n points,\n palette: [...output.palette],\n drawings: [...output.drawings],\n errors: [...output.errors],\n };\n}\n\n/**\n * The worker's side, apart from the worker so a test can run it on its own\n * thread: each run the page loads is kept here, so a tick sends one bar\n * and gets back the points from that bar on.\n */\nexport function createScriptHandler(\n scripts: readonly Script<ScriptInputs>[],\n post: ScriptWorkerPost,\n): (request: ScriptWorkerRequest) => void {\n const byId = new Map(scripts.map((script) => [script.id, script]));\n const runs = new Map<number, ScriptRun>();\n const fail = (run: number, seq: number, message: string) => post({ type: 'failed', run, seq, message });\n\n return (request) => {\n if (request.type === 'drop') {\n runs.delete(request.run);\n return;\n }\n if (request.type === 'load') {\n runs.delete(request.run);\n const script = byId.get(request.script);\n if (!script) return fail(request.run, request.seq, `no script '${request.script}' in this worker: give it to serveScripts`);\n try {\n const run = new ScriptRun(script, request.params, request.options);\n run.load(request.bars);\n runs.set(request.run, run);\n post(patchOf(request.run, request.seq, run, 0));\n } catch (error) {\n fail(request.run, request.seq, messageOf(error));\n }\n return;\n }\n const run = runs.get(request.run);\n if (!run) return fail(request.run, request.seq, `no run ${request.run} here: load it first`);\n // A new bar closes the one before, which runs again.\n const from = run.length - 1;\n try {\n if (request.type === 'tick') run.tick(request.bar);\n else run.next(request.bar);\n post(patchOf(request.run, request.seq, run, Math.max(0, from)));\n } catch (error) {\n // Always an answer: the page waits for one in order.\n runs.delete(request.run);\n fail(request.run, request.seq, messageOf(error));\n }\n };\n}\n\n/**\n * Serve `scripts` from a worker: call it in the worker's module, with the\n * scripts the page runs through `scriptWorkerIndicator`.\n *\n * ```ts\n * // scripts.worker.ts\n * import { serveScripts } from '@tradecanvas/script'\n * import { emaCross } from './emaCross'\n * serveScripts([emaCross])\n * ```\n */\nexport function serveScripts(scripts: readonly Script<ScriptInputs>[], scope: ScriptWorkerScope = self as unknown as ScriptWorkerScope): void {\n const handle = createScriptHandler(scripts, (message) => scope.postMessage(message));\n scope.addEventListener('message', (event) => handle(event.data as ScriptWorkerRequest));\n}\n"],"mappings":";;;AA2OA,SAAgB,EAA6D,GAA4C;AACvH,KAAI,OAAO,EAAW,MAAO,YAAY,EAAW,GAAG,MAAM,KAAK,GAAI,OAAU,MAAM,qCAAqC;AAC3H,KAAI,OAAO,EAAW,SAAU,WAAY,OAAU,MAAM,iBAAiB,EAAW,GAAG,qCAAqC;AAChI,QAAO,OAAO,OAAO;EAAE,GAAG;EAAY,MAAM;EAAmB,CAAC;;AASlE,SAAgB,EAAW,GAAc,GAAsC;CAC7E,IAAM,IAAW,EAAM;AACvB,KAAI,OAAO,KAAa,UAAU;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AAK,cAAc,EAAQ,OAAO,2CAA2C;AAC3H,OAAI;IACF,IAAM,IAAM,IAAI,EAAU,GAAQ,EAAQ,QAAQ,EAAQ,QAAQ;AAGlE,IAFA,EAAI,KAAK,EAAQ,KAAK,EACtB,EAAK,IAAI,EAAQ,KAAK,EAAI,EAC1B,EAAK,GAAQ,EAAQ,KAAK,EAAQ,KAAK,GAAK,EAAE,CAAC;YACxC,GAAO;AACd,MAAK,EAAQ,KAAK,EAAQ,KAAK,EAAU,EAAM,CAAC;;AAElD;;EAEF,IAAM,IAAM,EAAK,IAAI,EAAQ,IAAI;AACjC,MAAI,CAAC,EAAK,QAAO,EAAK,EAAQ,KAAK,EAAQ,KAAK,UAAU,EAAQ,IAAI,sBAAsB;EAE5F,IAAM,IAAO,EAAI,SAAS;AAC1B,MAAI;AAGF,GAFI,EAAQ,SAAS,SAAQ,EAAI,KAAK,EAAQ,IAAI,GAC7C,EAAI,KAAK,EAAQ,IAAI,EAC1B,EAAK,GAAQ,EAAQ,KAAK,EAAQ,KAAK,GAAK,KAAK,IAAI,GAAG,EAAK,CAAC,CAAC;WACxD,GAAO;AAGd,GADA,EAAK,OAAO,EAAQ,IAAI,EACxB,EAAK,EAAQ,KAAK,EAAQ,KAAK,EAAU,EAAM,CAAC;;;;AAgBtD,SAAgB,GAAa,GAA0C,IAA2B,MAA4C;CAC5I,IAAM,IAAS,GAAoB,IAAU,MAAY,EAAM,YAAY,EAAQ,CAAC;AACpF,GAAM,iBAAiB,YAAY,MAAU,EAAO,EAAM,KAA4B,CAAC"}
@@ -0,0 +1,30 @@
1
+ import { Scope } from './scope.js';
2
+ /** How far a run may go before the script is stopped, at the bar that went past. */
3
+ export interface ScriptLimits {
4
+ /** The most loop steps one bar takes, each counted by `loop()`. Default 1,000,000. */
5
+ loopSteps?: number;
6
+ /** The most numbers one `state.array` holds. Default 100,000. */
7
+ arraySize?: number;
8
+ /**
9
+ * The most ms one `load`, `tick` or `next` runs for, read after each bar.
10
+ * Unset: no limit. A bar that never returns is not stopped by this: only
11
+ * a worker can be stopped from outside.
12
+ */
13
+ runMs?: number;
14
+ }
15
+ /** Which limit a script went past. */
16
+ export type ScriptLimit = 'loop' | 'array' | 'time';
17
+ export declare const DEFAULT_LIMITS: Readonly<Required<ScriptLimits>>;
18
+ /** A limit gone past: what stops the bar. */
19
+ export declare class ScriptLimitError extends Error {
20
+ readonly limit: ScriptLimit;
21
+ constructor(limit: ScriptLimit, message: string);
22
+ }
23
+ /** The limits given, each checked, the rest at their defaults. */
24
+ export declare function limitsOf(given?: ScriptLimits): Required<ScriptLimits>;
25
+ /**
26
+ * Stop the bar for `limit`. The run keeps it too, so a script that catches
27
+ * the error and goes on is stopped all the same once the bar returns.
28
+ */
29
+ export declare function overLimit(scope: Scope, limit: ScriptLimit, message: string): never;
30
+ //# sourceMappingURL=limits.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limits.d.ts","sourceRoot":"","sources":["../src/limits.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAExC,oFAAoF;AACpF,MAAM,WAAW,YAAY;IAC3B,sFAAsF;IACtF,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iEAAiE;IACjE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,sCAAsC;AACtC,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;AAEpD,eAAO,MAAM,cAAc,EAAE,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC,CAI3D,CAAC;AAEF,6CAA6C;AAC7C,qBAAa,gBAAiB,SAAQ,KAAK;IAC7B,QAAQ,CAAC,KAAK,EAAE,WAAW;gBAAlB,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM;CAIzD;AAED,kEAAkE;AAClE,wBAAgB,QAAQ,CAAC,KAAK,GAAE,YAAiB,GAAG,QAAQ,CAAC,YAAY,CAAC,CAWzE;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,GAAG,KAAK,CAIlF"}
@@ -0,0 +1,129 @@
1
+ import { IndicatorDrawing, IndicatorMarkerShape, LineStyle } from '@tradecanvas/commons';
2
+ import { ScriptDrawings } from './drawings.js';
3
+ import { ScriptLimit } from './limits.js';
4
+ import { BarColorHandle, AlertConditionHandle, AlertConditionOptions, BackgroundHandle, BackgroundOptions, FillHandle, FillOptions, HlineOptions, PlotHandle, PlotOptions, ScriptPlotKind, ShapeHandle, ShapeOptions, ShapePosition } from './defineScript.js';
5
+ import { Scope } from './scope.js';
6
+ export interface PlotDeclaration {
7
+ readonly title: string;
8
+ readonly kind: ScriptPlotKind;
9
+ readonly color?: string;
10
+ readonly width?: number;
11
+ }
12
+ export interface ShapeDeclaration {
13
+ readonly title: string;
14
+ readonly shape: IndicatorMarkerShape;
15
+ readonly position: ShapePosition;
16
+ readonly color?: string;
17
+ }
18
+ export interface LevelDeclaration {
19
+ readonly price: number;
20
+ readonly color?: string;
21
+ readonly lineStyle?: LineStyle;
22
+ readonly title?: string;
23
+ }
24
+ export interface FillDeclaration {
25
+ /** The two plots it shades between, by their place among the plots. */
26
+ readonly between: readonly [number, number];
27
+ readonly color?: string;
28
+ }
29
+ export interface BackgroundDeclaration {
30
+ readonly title: string;
31
+ }
32
+ export interface AlertConditionDeclaration {
33
+ readonly title: string;
34
+ readonly message?: string;
35
+ }
36
+ /** What a script draws, known once its setup has run. */
37
+ export interface ScriptDeclarations {
38
+ readonly overlay: boolean;
39
+ readonly plots: readonly PlotDeclaration[];
40
+ readonly shapes: readonly ShapeDeclaration[];
41
+ readonly levels: readonly LevelDeclaration[];
42
+ readonly fills: readonly FillDeclaration[];
43
+ readonly backgrounds: readonly BackgroundDeclaration[];
44
+ /** How many `barcolor()` the script asked for. */
45
+ readonly barColors: number;
46
+ readonly alertConditions: readonly AlertConditionDeclaration[];
47
+ }
48
+ /** A colour a bar, by its place in the output's `palette` plus one: 0 for none. */
49
+ export type BarColors = Uint16Array;
50
+ /** A plot's values, a bar each, and the colour each bar was given. */
51
+ export interface PlotOutput extends PlotDeclaration {
52
+ readonly values: Float64Array;
53
+ /** Each bar's colour: 0 for the plot's own. */
54
+ readonly colors: BarColors;
55
+ }
56
+ export interface ShapeOutput extends ShapeDeclaration {
57
+ /** 1 on the bars it marks. */
58
+ readonly on: Uint8Array;
59
+ }
60
+ export interface FillOutput extends FillDeclaration {
61
+ /** Each bar's colour: 0 for the fill's own. */
62
+ readonly colors: BarColors;
63
+ }
64
+ export interface BackgroundOutput extends BackgroundDeclaration {
65
+ /** Each bar's colour: 0 for no background there. */
66
+ readonly colors: BarColors;
67
+ }
68
+ export interface AlertConditionOutput extends AlertConditionDeclaration {
69
+ /** 1 on the bars it holds. */
70
+ readonly on: Uint8Array;
71
+ }
72
+ export interface ScriptError {
73
+ /** The bar it stopped at. */
74
+ readonly bar: number;
75
+ readonly message: string;
76
+ /** The limit it went past, when that is why it stopped. */
77
+ readonly limit?: ScriptLimit;
78
+ }
79
+ /** What a run has drawn so far, a value a bar, without copying. */
80
+ export interface ScriptOutput {
81
+ readonly length: number;
82
+ readonly plots: readonly PlotOutput[];
83
+ readonly shapes: readonly ShapeOutput[];
84
+ readonly levels: readonly LevelDeclaration[];
85
+ readonly fills: readonly FillOutput[];
86
+ readonly backgrounds: readonly BackgroundOutput[];
87
+ /** Each `barcolor()`'s colour a bar: 0 for the chart's own. */
88
+ readonly barColors: readonly BarColors[];
89
+ readonly alertConditions: readonly AlertConditionOutput[];
90
+ /** The colours bars were given, each once. */
91
+ readonly palette: readonly string[];
92
+ /** The labels, lines and boxes it keeps, in the order made. */
93
+ readonly drawings: readonly IndicatorDrawing[];
94
+ readonly errors: readonly ScriptError[];
95
+ }
96
+ /** The plots, marks, fills, backgrounds and levels a script declares, and what its bars set in them. */
97
+ export declare class Outputs {
98
+ private readonly scope;
99
+ private readonly plots;
100
+ private readonly handles;
101
+ private readonly shapes;
102
+ private readonly fills;
103
+ private readonly backgrounds;
104
+ private readonly conditions;
105
+ private readonly barColorSlots;
106
+ private readonly levels;
107
+ private readonly drawingLists;
108
+ private readonly palette;
109
+ private readonly paletteIndex;
110
+ private open;
111
+ constructor(scope: Scope);
112
+ /** No more plots, marks or levels: the setup is over. */
113
+ close(): void;
114
+ private declaring;
115
+ /** A colour's place in the palette plus one. */
116
+ private colorIndex;
117
+ plot(title: string, options?: PlotOptions): PlotHandle;
118
+ shape(title: string, options?: ShapeOptions): ShapeHandle;
119
+ fill(a: PlotHandle, b: PlotHandle, options?: FillOptions): FillHandle;
120
+ bgcolor(options?: BackgroundOptions): BackgroundHandle;
121
+ /** Shapes the script draws, listed with its output. */
122
+ addDrawings(list: ScriptDrawings): ScriptDrawings;
123
+ barcolor(): BarColorHandle;
124
+ alertCondition(title: string, options?: AlertConditionOptions): AlertConditionHandle;
125
+ hline(price: number, options?: HlineOptions): void;
126
+ declarations(overlay: boolean): ScriptDeclarations;
127
+ output(length: number, errors: readonly ScriptError[]): ScriptOutput;
128
+ }
129
+ //# sourceMappingURL=outputs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outputs.d.ts","sourceRoot":"","sources":["../src/outputs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,KAAK,EACV,cAAc,EACd,oBAAoB,EACpB,qBAAqB,EACrB,gBAAgB,EAChB,iBAAiB,EACjB,UAAU,EACV,WAAW,EACX,YAAY,EACZ,UAAU,EACV,WAAW,EACX,cAAc,EACd,WAAW,EACX,YAAY,EACZ,a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C,YAAY,CAA6B;IAC1D,OAAO,CAAC,IAAI,CAAQ;gBAES,KAAK,EAAE,KAAK;IAczC,yDAAyD;IACzD,KAAK,IAAI,IAAI;IAIb,OAAO,CAAC,SAAS;IAIjB,gDAAgD;IAChD,OAAO,CAAC,UAAU;IAWlB,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,WAAgB,GAAG,UAAU;IAmB1D,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB,GAAG,WAAW;IAe7D,IAAI,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU,EAAE,OAAO,GAAE,WAAgB,GAAG,UAAU;IAiBzE,OAAO,CAAC,OAAO,GAAE,iBAAsB,GAAG,gBAAgB;IAW1D,uDAAuD;IACvD,WAAW,CAAC,IAAI,EAAE,cAAc,GAAG,cAAc;IAKjD,QAAQ,IAAI,cAAc;IAW1B,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,qBAA0B,GAAG,oBAAoB;IAYxF,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB,GAAG,IAAI;IAKtD,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,kBAAkB;IAalD,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,WAAW,EAAE,GAAG,YAAY;CAerE"}
@@ -0,0 +1,13 @@
1
+ import { IndicatorValue } from '@tradecanvas/commons';
2
+ import { ScriptOutput } from './outputs.js';
3
+ export declare const plotKey: (i: number) => string;
4
+ export declare const shapeKey: (i: number) => string;
5
+ export declare const backgroundKey: (i: number) => string;
6
+ export declare const barColorKey: (i: number) => string;
7
+ /** The field that holds a bar's colour, by its place in the output's palette. */
8
+ export declare const colorKey: (key: string) => string;
9
+ export declare const fillColorKey: (i: number) => string;
10
+ export declare const conditionKey: (i: number) => string;
11
+ /** Bar `i`'s values under their keys, or null when it has none. */
12
+ export declare function pointAt(output: ScriptOutput, i: number): IndicatorValue | null;
13
+ //# sourceMappingURL=points.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"points.d.ts","sourceRoot":"","sources":["../src/points.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAa,YAAY,EAAE,MAAM,cAAc,CAAC;AAO5D,eAAO,MAAM,OAAO,GAAI,GAAG,MAAM,WAAY,CAAC;AAC9C,eAAO,MAAM,QAAQ,GAAI,GAAG,MAAM,WAAY,CAAC;AAC/C,eAAO,MAAM,aAAa,GAAI,GAAG,MAAM,WAAa,CAAC;AACrD,eAAO,MAAM,WAAW,GAAI,GAAG,MAAM,WAAa,CAAC;AACnD,iFAAiF;AACjF,eAAO,MAAM,QAAQ,GAAI,KAAK,MAAM,WAAc,CAAC;AACnD,eAAO,MAAM,YAAY,GAAI,GAAG,MAAM,WAAa,CAAC;AACpD,eAAO,MAAM,YAAY,GAAI,GAAG,MAAM,WAAY,CAAC;AAQnD,mEAAmE;AACnE,wBAAgB,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,CAAC,EAAE,MAAM,GAAG,cAAc,GAAG,IAAI,CA4B9E"}