oakscriptjs 0.25.0 → 0.25.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/script/index.d.ts +2 -0
- package/dist/cjs/script/index.d.ts.map +1 -1
- package/dist/cjs/script/index.js.map +2 -2
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/script/index.d.ts +2 -0
- package/dist/esm/script/index.d.ts.map +1 -1
- package/dist/esm/script/index.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +1 -1
- package/src/script/index.ts +2 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/script/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview PineScript-style script API \u2014 write an indicator as a flat\n * script instead of the explicit calculate() convention.\n *\n * ```typescript\n * import { indicator, input, plot, ta } from 'oakscriptjs/script';\n *\n * indicator('My SMA', { overlay: true });\n * const length = input.int(20, 'Length', { minval: 1 });\n * const src = input.source('close', 'Source');\n * plot(ta.sma(src, length), 'SMA', { color: '#2962FF' });\n * ```\n *\n * Execution model: the host calls {@link executeScript} with the script body,\n * the bars and the current input values. Declaration calls (indicator, input.*,\n * plot, hline, fill, alertcondition, alert) run as the body executes and are collected\n * into a {@link ScriptRunResult}: the declarative configs (inputConfig,\n * plotConfig, hlineConfig, fillConfig) plus an IndicatorResult with the plot\n * data. Re-running the body with new bars or inputs is PineScript's\n * recalculation model.\n *\n * `input.*` is idempotent like PineScript: it declares the input AND returns\n * its current value (the host-supplied override, else the default).\n *\n * The OHLCV builtins (open/high/low/close/volume/hl2/hlc3/ohlc4/hlcc4) are\n * Series bound to a module-level BarData that the host swaps per run, so\n * derived Series memoize between identical runs and recompute when the bars\n * version bumps.\n *\n * One script executes at a time (module-level context) \u2014 hosts that run many\n * scripts must serialize executions, which a Web Worker does naturally.\n *\n * @module script\n */\n\nimport type { Bar } from '../types/index.js';\nimport type {\n ArrowData,\n BarColorData,\n BgColorData,\n BoxData,\n FillData,\n FillGradient,\n IndicatorResult,\n LabelData,\n LabelStyle,\n LineDrawingData,\n LinefillData,\n MarkerData,\n MarkerLocation,\n MarkerPosition,\n MarkerShape,\n MarkerSize,\n PineSize,\n PlotBarData,\n PlotCandleData,\n PolylineData,\n ShapeStyle,\n TableCellData,\n TableData,\n TableMergeData,\n TablePosition,\n TimeValue,\n} from '../types/metadata.js';\nimport type {\n ArrowConfig,\n BarColorConfig,\n CandleConfig,\n FillConfig,\n HLineConfig,\n InputConfig,\n InputCondition,\n PlotConfig,\n ShapeConfig,\n} from '../runtime/types.js';\nimport { BarData, Series, MAX_BARS_BACK, historyError } from '../runtime/series.js';\nimport * as taSeries from '../ta-series.js';\nimport type { TaNamespace } from './api/ta.js';\nimport type { StrategyNamespace } from './api/strategy.js';\nimport type {\n BarmergeNamespace,\n BarstateNamespace,\n ChartNamespace,\n DividendsNamespace,\n EarningsNamespace,\n RequestNamespace,\n SessionNamespace,\n SplitsNamespace,\n SyminfoNamespace,\n TickerNamespace,\n TimeframeNamespace,\n} from './api/context.js';\nimport type { CalcNamespace } from './api/calc.js';\nimport type { ColorNamespace } from './api/color.js';\nimport type { LogNamespace } from './api/log.js';\nimport type { AlertApi } from './api/alert.js';\nimport type { TableNamespace } from './api/table.js';\nimport { taStep, type BarStep } from '../ta/step.js';\nimport * as incremental from './incremental.js';\nimport { outerWrites } from './closure-writes.js';\nimport * as pineConstants from './constants.js';\nimport { drawingNamespace, isPlainObject, namedArguments, unknownArgument } from './drawing-args.js';\nimport * as colorCore from '../color/index.js';\nimport * as compareCore from '../compare/index.js';\nimport { inputColorDefault, isColorText } from '../color/parse.js';\nimport { fixnan as fixnanValues, isNA, nz as nzValue } from '../utils/index.js';\nimport { externalSource } from '../utils/source-resolver.js';\nimport * as lineCore from '../line/index.js';\nimport * as labelCore from '../label/index.js';\nimport * as boxCore from '../box/index.js';\nimport * as linefillCore from '../linefill/index.js';\nimport * as polylineCore from '../polyline/index.js';\nimport * as tableCore from '../table/index.js';\nimport * as chartPointCore from '../chartpoint/index.js';\nimport * as textCore from '../text/index.js';\nimport * as mathCore from '../math/index.js';\nimport {\n createdDrawingKinds,\n droppedDrawings,\n resetDrawings,\n restoreDrawingCheckpoint,\n restoreDrawingState,\n saveDrawingCheckpoint,\n saveDrawingState,\n setDrawingBar,\n setDrawingLimits,\n holdDrawing,\n releaseDrawing,\n type DrawingKind,\n type DrawingVariable,\n} from '../drawing/registry.js';\nexport { holdDrawing, releaseDrawing, type DrawingVariable } from '../drawing/registry.js';\n\n/**\n * A variable that holds one drawing (a line, label, box...) from bar to bar and keeps it alive: the object it holds is\n * never deleted by the `max_*_count` limit of the script. Use it to create one object and move it, instead of a new\n * object on each bar. Assigning another object (or `undefined` for na) releases the one before, which the limit can\n * delete again. Declare it in the script body (outside the bar loops), then read and write `.value` in a bar loop.\n * @param initial - The object held from the start. Default: none (`.value` is `undefined`).\n * @returns A box whose `.value` is the held object, or `undefined`.\n * @example\n * ```js\n * const level = varDrawing();\n * eachBar((c) => {\n * if (c.i === c.n - 1) level.value = line.new(c.i - 20, c.close, c.i, c.close, { color: color.orange });\n * });\n * ```\n */\n// Without an initial object the kind is not known: `.value` is any drawing, so `line.delete(v.value)` checks.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function varDrawing<T extends object = any>(initial?: T): DrawingVariable<T> {\n const box = persist<T | undefined>(initial ? holdDrawing(initial) : undefined);\n return {\n get value() {\n return box.value;\n },\n set value(next: T | undefined) {\n const current = box.value;\n if (next === current) return;\n releaseDrawing(current);\n box.value = next ? holdDrawing(next) : undefined;\n },\n };\n}\nimport { drawingOutputs } from '../drawing/output.js';\nimport * as timeframeCore from '../timeframe/index.js';\nimport * as timeCore from '../time/index.js';\nimport * as strCore from '../str/index.js';\nimport { formatMessage } from '../str/messageformat.js';\nimport { tickScale } from '../str/numberformat.js';\nimport { TradingCalendar, type SessionSpec } from '../session/calendar.js';\nimport { SessionBars, sessionFlags, strayPeriods, type SessionFlags } from '../session/bars.js';\nimport { afterCompletion, heikinAshi, mapToChart, periodsOf, resample } from '../security/resample.js';\nimport { securityLowerTf, securityOther, type OtherSymbolChart } from '../security/other.js';\nimport { eventsOnBars } from '../security/events.js';\nimport { position } from '../types/index.js';\nimport type { Box, ChartPoint, Label, Line, Linefill, Polyline, Table } from '../types/index.js';\nimport {\n STRATEGY_CONSTANTS,\n STRATEGY_DEFAULTS,\n STRATEGY_NUMBER_VARIABLES,\n STRATEGY_TEXT_VARIABLES,\n type StrategyCloseAllOptions,\n type StrategyCloseOptions,\n type StrategyDirection,\n type StrategyEngine,\n type StrategyEntryOptions,\n type StrategyExitOptions,\n type StrategyNumberVariable,\n type StrategyOptions,\n type StrategyProperties,\n type StrategyRiskDirection,\n type StrategyRiskRule,\n type StrategyRiskValueType,\n type StrategyTextVariable,\n type StrategyTrade,\n type StrategyVariable,\n} from '../strategy/index.js';\nimport { sessionPeriods, type SessionPeriods } from '../session/context.js';\n\n/** Everything one run of a script produced. */\nexport interface ScriptRunResult {\n metadata: {\n title: string;\n shortTitle?: string;\n overlay: boolean;\n precision?: number;\n format?: string;\n scale?: 'right' | 'left' | 'none';\n /** indicator(..., { pane }) when the script gives it (not PineScript); `overlay` is the pane it gave. */\n pane?: 'price' | 'separate' | 'auto';\n };\n inputConfig: InputConfig[];\n plotConfig: PlotConfig[];\n hlineConfig: HLineConfig[];\n fillConfig: FillConfig[];\n shapeConfig: ShapeConfig[];\n arrowConfig: ArrowConfig[];\n barColorConfig: BarColorConfig[];\n /** plotcandle() / plotbar() declarations */\n candleConfig: CandleConfig[];\n /**\n * The kinds of drawing objects (label.new, line.new, box.new, linefill.new, polyline.new, table.new) the run\n * created, even the ones deleted since: the drawing groups a user can show or hide.\n */\n drawingKinds: DrawingKind[];\n /**\n * The plot(), plotshape(), plotchar(), plotarrow(), plotcandle() and plotbar() declarations in the order the\n * script made them (the id of each in its own config). PineScript numbers a script's outputs in this order.\n */\n outputs: ScriptOutput[];\n defaultInputs: Record<string, unknown>;\n alertConfig: AlertConditionConfig[];\n /** Strategy properties (declared values, else the PineScript defaults) when the script declares strategy(). */\n strategyConfig?: StrategyProperties;\n /**\n * The renderable output: plots keyed by plotConfig ids, plot-pair fills, markers, arrows, background and bar\n * colours, candles and bars, and the drawings (labels, lines, boxes, linefills, polylines, tables) alive after the\n * last bar. `outputValues`: per plotshape() / plotchar() / plotarrow() id, the value of its series on each bar where\n * it is not na (a condition gives 1 or 0), at the bar it was computed on (the offset not applied).\n */\n result: IndicatorResult & { alerts?: AlertState[]; alertCalls?: AlertCall[]; outputValues?: Record<string, TimeValue[]>; logs?: LogEntry[] };\n /** The script called alert() during the run (PineScript `hasAlertFunction` is known at compile time: a host that\n * needs it before any bar runs reads the source). */\n hasAlertFunction: boolean;\n /** The script read `chart.left_visible_bar_time` or `chart.right_visible_bar_time`: it has to be calculated again when\n * the visible range of the chart changes. */\n usesVisibleRange: boolean;\n /**\n * Things the run did that a script usually does not mean, in plain words: drawings deleted because there were more\n * than the maximum count (`indicator(max_labels_count)`...). Empty when there is nothing to say.\n */\n warnings: string[];\n}\n\nexport interface AlertConditionConfig {\n id: string;\n title: string;\n message?: string;\n}\n\n/** Per-run alert evaluation: whether the condition is true on the last bar, and on which bars it is true. */\nexport interface AlertState {\n id: string;\n title: string;\n message?: string;\n triggered: boolean;\n /** Times of the bars (as given in the input bars) on which the condition is true (not na, not 0), oldest first. */\n times: number[];\n}\n\n/** How often an alert() call may trigger the alert (PineScript `alert.freq_*`). */\nexport type AlertFrequency = 'all' | 'once_per_bar' | 'once_per_bar_close';\n\n/** One alert() call: the time of the bar it ran on (as given in the input bars), its message and frequency. */\nexport interface AlertCall {\n time: number;\n message: string;\n freq: AlertFrequency;\n}\n\n/** One output declaration of a script: plot(), plotshape() ('shape'), plotchar() ('char'), plotarrow() ('arrow'),\n * plotcandle() ('candle') or plotbar() ('bar'), with its id in plotConfig / shapeConfig / arrowConfig / candleConfig. */\nexport interface ScriptOutput {\n kind: 'plot' | 'shape' | 'char' | 'arrow' | 'candle' | 'bar';\n id: string;\n title?: string;\n}\n\n/** Handle returned by plot()/hline() so fill() can reference them. */\nexport interface PlotHandle {\n id: string;\n kind: 'plot' | 'hline';\n}\n\ninterface Collector {\n declaration?: 'indicator' | 'strategy';\n title: string;\n shortTitle?: string;\n overlay: boolean;\n precision?: number;\n format?: string;\n /** indicator(..., { scale }): the price scale the script uses. */\n scale?: 'right' | 'left' | 'none';\n inputValues: Record<string, unknown>;\n inputConfig: InputConfig[];\n inputIds: Set<string>;\n defaultInputs: Record<string, unknown>;\n plotConfig: PlotConfig[];\n plots: Record<string, TimeValue[]>;\n hlineConfig: HLineConfig[];\n fills: FillData[];\n fillConfig: FillConfig[];\n shapeConfig: ShapeConfig[];\n markers: MarkerData[];\n outputValues: Record<string, TimeValue[]>;\n arrowConfig: ArrowConfig[];\n arrows: ArrowData[];\n barColorConfig: BarColorConfig[];\n bgColors: BgColorData[];\n barColors: BarColorData[];\n candleConfig: CandleConfig[];\n plotCandles: Record<string, PlotCandleData[]>;\n plotBars: Record<string, PlotBarData[]>;\n outputs: ScriptOutput[];\n alertConfig: AlertConditionConfig[];\n alerts: AlertState[];\n alertCalls: AlertCall[];\n /** log.*() messages of the run. */\n logs: LogEntry[];\n hasAlertFunction: boolean;\n usesVisibleRange: boolean;\n strategy?: StrategyRun;\n /** Strict mode (`ScriptOptions.strict`): mistakes are errors. */\n strict: boolean;\n /** indicator(..., { pane: 'auto' }): the pane is chosen from the plotted values at the end of the run. */\n paneAuto?: boolean;\n /** indicator(..., { pane }) as given. */\n pane?: 'price' | 'separate' | 'auto';\n /** Plot ids taken (`ScriptOptions.plotIds` 'title'). */\n plotIdsTaken?: Set<string>;\n /** Plots that took a colour of the palette so far. */\n paletteUsed?: number;\n}\n\n/** State of the strategy of the current run. */\ninterface StrategyRun {\n properties: StrategyProperties;\n engine?: StrategyEngine;\n /** strategy.eachBar() has run (it runs once per script run). */\n looped: boolean;\n /** Inside the strategy.eachBar() callback. */\n inLoop: boolean;\n}\n\n/** Bars for the current run. Module-level and REUSED across runs so builtins\n * and every Series derived from them keep their version-keyed memoization. */\nconst ctxBars = new BarData([]);\n\nlet ctx: Collector | null = null;\n\nfunction collector(): Collector {\n if (!ctx) {\n throw new Error(\n 'oakscriptjs/script functions can only run inside executeScript() \u2014 ' +\n 'the host (chart/worker) drives script execution.'\n );\n }\n return ctx;\n}\n\nfunction freshCollector(inputValues: Record<string, unknown>, strict = false): Collector {\n return {\n strict,\n title: 'Untitled',\n overlay: false,\n inputValues,\n inputConfig: [],\n inputIds: new Set(),\n defaultInputs: {},\n plotConfig: [],\n plots: {},\n hlineConfig: [],\n fills: [],\n fillConfig: [],\n shapeConfig: [],\n markers: [],\n outputValues: {},\n arrowConfig: [],\n arrows: [],\n barColorConfig: [],\n bgColors: [],\n barColors: [],\n candleConfig: [],\n plotCandles: {},\n plotBars: {},\n outputs: [],\n alertConfig: [],\n alerts: [],\n alertCalls: [],\n logs: [],\n hasAlertFunction: false,\n usesVisibleRange: false,\n };\n}\n\n/** Stable input id from the title (\"ATR / Range Period\" \u2192 \"atr_range_period\"). */\nfunction slugId(title: string | undefined, fallback: string, taken: Set<string>): string {\n const base =\n (title ?? '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '') || fallback;\n let id = base;\n for (let n = 2; taken.has(id); n++) id = `${base}_${n}`;\n taken.add(id);\n return id;\n}\n\n/** A value as it is written in a script, for messages. */\nfunction shown(v: unknown): string {\n if (typeof v === 'string') return JSON.stringify(v);\n if (typeof v === 'number' || typeof v === 'boolean' || v === null || v === undefined) return String(v);\n return Array.isArray(v) ? 'a list' : typeof v === 'object' ? 'an object' : typeof v;\n}\n\n/** Up to three of `names` close to `name` (spelling mistakes), closest first. */\nfunction closeNames(name: string, names: readonly string[]): string[] {\n const bare = (x: string) => x.toLowerCase().replace(/[^a-z0-9]/g, '');\n const same = names.filter((k) => bare(k) === bare(name));\n if (same.length) return same;\n const n = name.toLowerCase();\n const dist = (a: string, b: string): number => {\n const row = Array.from({ length: b.length + 1 }, (_, j) => j);\n for (let i = 1; i <= a.length; i++) {\n let diag = row[0]!;\n row[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const up = row[j]!;\n row[j] = Math.min(up + 1, row[j - 1]! + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));\n diag = up;\n }\n }\n return row[b.length]!;\n };\n return names\n .map((k) => ({ k, d: dist(n, k.toLowerCase()) }))\n .filter(({ k, d }) => d <= Math.max(2, Math.floor(name.length / 3)) || k.toLowerCase().includes(n) || n.includes(k.toLowerCase()))\n .sort((a, b) => a.d - b.d)\n .slice(0, 3)\n .map(({ k }) => k);\n}\n\n/** Strict mode: every input value given by the host has a name the script declares. */\nfunction checkInputNames(c: Collector, inputs: Record<string, unknown>): void {\n const names = c.inputConfig.map((i) => i.id);\n for (const key of Object.keys(inputs)) {\n if (c.inputIds.has(key)) continue;\n const near = closeNames(key, names);\n throw new ScriptError(\n `There is no input \"${key}\".` + (near.length ? ` Did you mean \"${near.join('\", \"')}\"?` : '') +\n (names.length ? ` The inputs are: ${names.join(', ')}.` : ' The script has no inputs.')\n );\n }\n}\n\n/** Strict mode: the value the host gives an input has its type, range and options. */\nfunction checkInputValue(config: InputConfig, id: string, value: unknown): void {\n const name = config.title ? `\"${config.title}\" (${id})` : `\"${id}\"`;\n const fail = (why: string): never => {\n throw new ScriptError(`Input ${name}: ${why}`);\n };\n switch (config.type) {\n case 'int':\n case 'float':\n case 'price':\n case 'time':\n if (typeof value !== 'number' || Number.isNaN(value)) fail(`${shown(value)} is not a number.`);\n if (config.type === 'int' && !Number.isInteger(value)) fail(`${value} is not a whole number.`);\n if (config.min !== undefined && (value as number) < config.min) fail(`${value} is below the minimum, ${config.min}.`);\n if (config.max !== undefined && (value as number) > config.max) fail(`${value} is above the maximum, ${config.max}.`);\n break;\n case 'bool':\n if (typeof value !== 'boolean') fail(`${shown(value)} is not true or false.`);\n break;\n case 'color':\n if (!isColorText(value)) fail(`${shown(value)} is not a colour. Write it as \"#ff0000\" or \"rgba(255, 0, 0, 0.5)\".`);\n break;\n case 'source':\n if (typeof value !== 'string' || (!SOURCES[value] && !externalSource(value))) {\n fail(`${shown(value)} is not a price source. The sources are: ${Object.keys(SOURCES).join(', ')}.`);\n }\n break;\n default:\n if (typeof value !== 'string') fail(`${shown(value)} is not a text.`);\n }\n if (config.options && !config.options.includes(value as string | number)) {\n fail(`${shown(value)} is not one of the choices: ${config.options.map(shown).join(', ')}.`);\n }\n}\n\n/** Strict mode: the named options of a declaration call are known and its colours are colours. */\nfunction checkOptions(fn: string, options: object | undefined, keys: readonly string[], colorKeys: readonly string[] = ['color']): void {\n if (!ctx?.strict || options === undefined) return;\n if (!isPlainObject(options)) throw new ScriptError(`${fn}(): the options are an object, e.g. { color: color.red }.`);\n for (const [key, v] of Object.entries(options)) {\n if (!keys.includes(key)) {\n const near = closeNames(key, keys);\n throw new ScriptError(\n `${fn}(): there is no option \"${key}\".` + (near.length ? ` Did you mean \"${near.join('\", \"')}\"?` : '') +\n ` The options are: ${keys.join(', ')}.`\n );\n }\n if (colorKeys.includes(key)) checkColor(`${fn}(): the ${key}`, v);\n }\n}\n\n/** Strict mode: a colour argument (a colour or per-bar colours; na entries are allowed) holds colours only. */\nfunction checkColor(what: string, v: unknown): void {\n if (v === undefined || v === null) return;\n const bad = Array.isArray(v) ? v.find((x) => x !== undefined && x !== null && x !== '' && !isColorText(x)) : isColorText(v) ? undefined : v;\n if (bad !== undefined) {\n const name = typeof bad === 'string' ? bad.trim().toLowerCase() : '';\n if (/^[a-z]+$/.test(name) && typeof (colorCore as Record<string, unknown>)[name] === 'string') {\n throw new ScriptError(`${what} ${shown(bad)} is a colour name: write color.${name} (without quotes).`);\n }\n throw new ScriptError(`${what} ${shown(bad)} is not a colour. Write a colour as color.red, \"#ff0000\" or \"rgba(255, 0, 0, 0.5)\".`);\n }\n}\n\n/** The warnings of the run that ends (see `ScriptRunResult.warnings`). */\nfunction runWarnings(): string[] {\n const out: string[] = [];\n const option: Record<string, string> = { line: 'max_lines_count', label: 'max_labels_count', box: 'max_boxes_count', polyline: 'max_polylines_count', linefill: 'max_lines_count' };\n for (const [kind, n] of Object.entries(droppedDrawings())) {\n if (!n || kind === 'table') continue;\n out.push(\n `${n} ${kind}${n > 1 ? 's were' : ' was'} deleted because the script made more than the maximum number of ${kind}s; ` +\n `the oldest go first. To keep more, raise ${option[kind]} in indicator(), e.g. indicator(\"...\", { ${option[kind]}: 500 }).`\n );\n }\n return out;\n}\n\n/**\n * indicator(..., { pane: 'auto' }): the plots belong on the price chart when nine values in ten (all plots together) are\n * within the price range of the bars, widened by a quarter on each side (plots with display 'none' do not count); a script\n * without plots goes on the price chart.\n */\nfunction plotsOnPrices(c: Collector): boolean {\n const b = ctxBars.bars;\n let lo = Infinity;\n let hi = -Infinity;\n for (const bar of b) {\n if (bar.low < lo) lo = bar.low;\n if (bar.high > hi) hi = bar.high;\n }\n if (!(hi >= lo)) return true;\n const margin = (hi - lo) * 0.25;\n let inside = 0;\n let total = 0;\n // the plots shown on the chart only (display 'none': values for alerts or other scripts)\n const shown = c.plotConfig.filter((p) => p.display !== 'none').map((p) => c.plots[p.id] ?? []);\n for (const points of shown) {\n for (const p of points) {\n total++;\n if (p.value >= lo - margin && p.value <= hi + margin) inside++;\n }\n }\n return total === 0 || inside >= total * 0.9;\n}\n\n// \u2500\u2500 Host entry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** What the host passes to its strategy engine factory when the script declares strategy(). */\nexport interface StrategySetup {\n properties: StrategyProperties;\n bars: readonly Bar[];\n chart: Readonly<ChartContext>;\n}\n\nexport interface ScriptOptions {\n /** Creates the order engine of a strategy script; called by strategy(). */\n strategyEngine?: (setup: StrategySetup) => StrategyEngine;\n /**\n * Records the strategy engine's answers of each bar and the `varip` values, for the intrabar runs of a strategy\n * (see {@link executeIntrabar}). The host keeps one recorder for the main run of a backtest and its intrabar runs.\n */\n recorder?: StrategyRecorder;\n /**\n * Strict mode: mistakes that PineScript lets pass silently throw a {@link ScriptError} with a plain message: an input\n * value of the wrong type, out of its range or not one of its options, an input name the script does not declare,\n * an unknown option of plot() / hline() / plotshape() / plotchar() / bgcolor() / barcolor(), a text that is not a\n * colour. Default false (PineScript behaviour); {@link defineIndicator} turns it on.\n */\n strict?: boolean;\n /**\n * Colours of the plots that give none: true for {@link DEFAULT_PALETTE} (each plot without a colour takes the next\n * one), or a list of colours. Default false: every plot without a colour is blue, as in PineScript.\n */\n palette?: boolean | readonly string[];\n /**\n * The ids of the plots in `plotConfig` and `result.plots`: 'index' (default, as PineScript numbers them: plot0,\n * plot1...) or 'title' (made from the title as the inputs' ids are: \"Fast MA\" gives fast_ma), which stay the same when\n * plots are added or moved.\n */\n plotIds?: 'index' | 'title';\n}\n\n/** The colours given in turn to plots without a colour when `ScriptOptions.palette` is true. */\nexport const DEFAULT_PALETTE: readonly string[] = ['#2962FF', '#FF6D00', '#00897B', '#AB47BC', '#F23645', '#43A047', '#FBC02D', '#8D6E63'];\n\n/** A mistake found in strict mode (see `ScriptOptions.strict`): the message says what to change. */\nexport class ScriptError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ScriptError';\n }\n}\n\nlet scriptOptions: ScriptOptions = {};\n\n/** The `varip` values of a replayed bar in a script without `varip`. */\nconst NO_VARIP: unknown[] = [];\n\n/** Intrabar run of the current run (see {@link executeIntrabar}); null in a main run. */\ninterface IntrabarRun {\n /** The bar calculated inside the bar: the last bar of the run. */\n bar: number;\n /** Bar index of the chart's last bar (`last_bar_index`, `barstate.islast`, `BarContext.n`). */\n lastBarIndex: number;\n engine: StrategyEngine;\n recorder: StrategyRecorder;\n}\nlet intrabarRun: IntrabarRun | null = null;\n\n/**\n * Answers of the strategy engine recorded in the main run of a strategy, bar by bar, and its `varip` values: an\n * intrabar run replays the bars before its bar from them (see {@link executeIntrabar}). Create one per backtest and\n * pass it to the main run (`ScriptOptions.recorder`) and to every intrabar run.\n */\nexport class StrategyRecorder {\n /** Per bar: the values the engine returned to the strategy.eachBar() callback (strategy.*, trades...), in order. */\n readonly answers: unknown[][] = [];\n /** Per bar: the `varip` values when the bar's strategy.eachBar() callback started in the main run. */\n readonly varipStarts: unknown[][] = [];\n /** Current `varip` values: kept through the intrabar runs (no rollback). */\n readonly varip: unknown[] = [];\n /**\n * Why the intrabar runs of this recorder calculate all the bars before their bar (a feature that is not resumed,\n * or a verification difference); null while they are resumed (see {@link executeIntrabar}).\n */\n get intrabarFullRunReason(): string | null {\n return intrabarChains.get(this)?.reason ?? null;\n }\n}\n\n/** Module state of a run, saved around a nested run (an intrabar run inside the bar loop of the main run). */\ninterface RunState {\n bars: Bar[];\n ctx: Collector | null;\n chartCtx: ChartContext;\n runNow: number;\n scriptOptions: ScriptOptions;\n currentBar: number;\n missingSymbols: SymbolDataRequest[];\n sessionCache: typeof sessionCache;\n intrabarRun: IntrabarRun | null;\n varip: VaripRun;\n drawings: ReturnType<typeof saveDrawingState>;\n random: ReturnType<typeof mathCore.saveRandom>;\n}\n\nfunction saveRunState(): RunState {\n return {\n bars: ctxBars.bars,\n ctx,\n chartCtx,\n runNow,\n scriptOptions,\n currentBar,\n missingSymbols,\n sessionCache,\n intrabarRun,\n varip: varipRun,\n drawings: saveDrawingState(),\n random: mathCore.saveRandom(),\n };\n}\n\nfunction restoreRunState(st: RunState): void {\n ctxBars.setAll(st.bars);\n ctx = st.ctx;\n chartCtx = st.chartCtx;\n runNow = st.runNow;\n scriptOptions = st.scriptOptions;\n currentBar = st.currentBar;\n missingSymbols = st.missingSymbols;\n sessionCache = st.sessionCache;\n intrabarRun = st.intrabarRun;\n varipRun = st.varip;\n restoreDrawingState(st.drawings);\n mathCore.restoreRandom(st.random);\n}\n\n/**\n * Runs a script body against `bars` with the given input overrides and\n * collects everything it declared. `chart` describes the bars (chart timeframe,\n * exchange time zone, session type) for the PineScript values that depend on them. `options.strategyEngine`\n * supplies the order engine of strategy scripts. This is the host-side entry \u2014 editor\n * panels, workers and tests call it; scripts never do.\n */\nexport function executeScript(\n body: () => void,\n barsInput: Bar[],\n inputs: Record<string, unknown> = {},\n chart: ChartContext = {},\n options: ScriptOptions = {}\n): ScriptRunResult {\n return runBody(body, barsInput, inputs, chart, options, null);\n}\n\n/** executeScript(), as part of an incremental run (`inc`, see createScriptRun) or alone (null). */\nfunction runBody(\n body: () => void,\n barsInput: Bar[],\n inputs: Record<string, unknown>,\n chart: ChartContext,\n options: ScriptOptions,\n inc: incremental.ActiveRun | null\n): ScriptRunResult {\n // A run inside another one (an intrabar run of a strategy) puts the outer run back when it ends.\n const outer = ctx ? saveRunState() : null;\n // A main run with a recorder starts a new backtest: its intrabar runs start again (#206).\n if (options.recorder) intrabarChains.delete(options.recorder);\n // A plain run inside an incremental one is not part of it.\n const outerInc = inc ? incremental.beginRun(inc) : incremental.suspendRun();\n ctxBars.setAll(barsInput);\n chartCtx = { ...chart };\n runNow = chart.now ?? Date.now();\n scriptOptions = options;\n ctx = freshCollector(inputs, options.strict === true);\n intrabarRun = null;\n varipRun = { slot: 0, recorder: options.recorder ?? null, mode: 'live', scratch: null };\n currentBar = -1;\n resetDrawings();\n mathCore.resetRandom();\n missingSymbols = [];\n try {\n try {\n body();\n } catch (err) {\n // An expression of request.security runs on no bar and without the symbol's properties while its bars are not\n // given (syminfo.sector there throws): the run waits for the data, not on the error.\n if (missingSymbols.length && !(err instanceof MissingSymbolDataError)) throw new MissingSymbolDataError(missingSymbols);\n throw err;\n }\n if (missingSymbols.length) throw new MissingSymbolDataError(missingSymbols);\n if (ctx.strict) checkInputNames(ctx, inputs);\n if (ctx.paneAuto) ctx.overlay = plotsOnPrices(ctx);\n // the outputs read the drawings: not a drawing of the script\n if (inc) incremental.bodyDone();\n const c = ctx;\n return {\n metadata: {\n title: c.title,\n shortTitle: c.shortTitle,\n overlay: c.overlay,\n precision: c.precision,\n format: c.format,\n ...(c.scale ? { scale: c.scale } : {}),\n ...(c.pane ? { pane: c.pane } : {}),\n },\n inputConfig: c.inputConfig,\n plotConfig: c.plotConfig,\n hlineConfig: c.hlineConfig,\n fillConfig: c.fillConfig,\n shapeConfig: c.shapeConfig,\n arrowConfig: c.arrowConfig,\n barColorConfig: c.barColorConfig,\n candleConfig: c.candleConfig,\n drawingKinds: createdDrawingKinds(),\n outputs: c.outputs,\n defaultInputs: c.defaultInputs,\n alertConfig: c.alertConfig,\n strategyConfig: c.strategy?.properties,\n result: {\n metadata: { title: c.title, shorttitle: c.shortTitle, overlay: c.overlay, precision: c.precision },\n plots: c.plots,\n fills: c.fills.length ? c.fills : undefined,\n markers: c.markers.length ? c.markers : undefined,\n outputValues: Object.keys(c.outputValues).length ? c.outputValues : undefined,\n arrows: c.arrows.length ? c.arrows : undefined,\n bgColors: c.bgColors.length ? c.bgColors : undefined,\n barColors: c.barColors.length ? c.barColors : undefined,\n plotCandles: Object.keys(c.plotCandles).length ? c.plotCandles : undefined,\n plotBars: Object.keys(c.plotBars).length ? c.plotBars : undefined,\n ...(intrabarRun ? {} : drawingOutputs(ctxBars.bars, chartCtx.timeUnit)),\n alerts: c.alerts.length ? c.alerts : undefined,\n alertCalls: c.alertCalls.length ? c.alertCalls : undefined,\n // By bar, in call order on each bar (the top-level calls make theirs on every bar at once).\n logs: c.logs.length ? [...c.logs].sort((x, y) => x.bar - y.bar).slice(-MAX_LOG_ENTRIES) : undefined,\n },\n hasAlertFunction: c.hasAlertFunction,\n usesVisibleRange: c.usesVisibleRange,\n warnings: runWarnings(),\n };\n } finally {\n ctx = null;\n if (outer) restoreRunState(outer);\n incremental.endRun(outerInc);\n }\n}\n\n/** What {@link executeIntrabar} needs besides the script. */\nexport interface IntrabarOptions {\n /** The bar calculated inside the bar: `bars` ends with it, as it stands at the tick (close = the tick price). */\n bar: number;\n /** Bar index of the chart's last bar (the main run's last bar). */\n lastBarIndex: number;\n /** The strategy engine of the main run: the order calls and `strategy.*` reads of bar `bar` go to it. */\n engine: StrategyEngine;\n /** The recorder of the main run. */\n recorder: StrategyRecorder;\n /**\n * Resume the run from the state at the start of the bar (default true, #206); false calculates all the bars before\n * it, as before.\n */\n resume?: boolean;\n /**\n * Resumed runs also calculated in full and compared, the first ones of a backtest (default 2): a difference makes the\n * next intrabar runs full ones (a script that keeps state outside persist() boxes).\n */\n verify?: number;\n}\n\n/** What {@link executeIntrabar} calculated. */\nexport interface IntrabarUpdate {\n /** First bar calculated: 0 for a full run, else the bar of the previous intrabar run (#206) */\n from: number;\n /** The run was resumed from the state of the bar before `from` */\n incremental: boolean;\n /** Why the intrabar runs of the backtest are full runs (null: resumed) */\n fullRunReason: string | null;\n}\n\n/** The intrabar runs of a backtest (one recorder): each one resumes from the state the previous one kept (#206). */\ninterface IntrabarChain {\n body: () => void;\n inputs: Record<string, unknown>;\n chart: ChartContext;\n engine: StrategyEngine;\n lastBarIndex: number;\n /** State kept by the last run (null: the next run is a full one that records it) */\n memory: incremental.RunMemory | null;\n /** Bars of the last run */\n n: number;\n reason: string | null;\n verifyLeft: number;\n}\nconst intrabarChains = new WeakMap<StrategyRecorder, IntrabarChain>();\n\n/**\n * The live engine of an intrabar run with its calls logged (`log`, to compare two runs) and its order calls, when\n * `writes` is given, kept there instead of made (a resumed run gives them to the engine once it has ended: a run\n * stopped in the middle makes none).\n */\nfunction intrabarEngine(engine: StrategyEngine, log: unknown[] | null, writes: Array<() => void> | null): StrategyEngine {\n const read = <T>(name: string, args: unknown[], value: T): T => {\n log?.push([name, ...args, value]);\n return value;\n };\n const write = (name: string, args: unknown[], call: () => void): void => {\n log?.push([name, ...args]);\n if (writes) writes.push(call);\n else call();\n };\n return {\n ...forward(engine),\n entry: (id, direction, options) => write('entry', [id, direction, options], () => engine.entry(id, direction, options)),\n order: (id, direction, options) => write('order', [id, direction, options], () => engine.order(id, direction, options)),\n exit: (id, options) => write('exit', [id, options], () => engine.exit(id, options)),\n close: (id, options) => write('close', [id, options], () => engine.close(id, options)),\n close_all: (options) => write('close_all', [options], () => engine.close_all(options)),\n cancel: (id) => write('cancel', [id], () => engine.cancel(id)),\n cancel_all: () => write('cancel_all', [], () => engine.cancel_all()),\n get: (name) => read('get', [name], engine.get(name)),\n openTrade: (index) => read('openTrade', [index], engine.openTrade(index)),\n closedTrade: (index) => read('closedTrade', [index], engine.closedTrade(index)),\n defaultEntryQty: engine.defaultEntryQty\n ? (price) => read('defaultEntryQty', [price], engine.defaultEntryQty!(price))\n : undefined,\n };\n}\n\n/** Puts the `varip` values back to a copy taken before a run. */\nfunction setVarip(recorder: StrategyRecorder, values: unknown[]): void {\n recorder.varip.length = 0;\n recorder.varip.push(...values);\n}\n\n/**\n * Host-side: runs a strategy once more on one bar, inside the bar (calculation on order fills, or on the ticks of\n * history bars). Scripts never call it. `bars` holds the bars up to that bar, the last one as it stands at the tick\n * (its close is the tick price, its high and low the extremes reached so far). The script's variables come back to\n * their state at the start of the bar, except `varip` ones. In strategy.eachBar(), the bars before replay the engine's\n * answers that the main run recorded (their order calls are dropped), and the bar itself calls `options.engine`\n * without processBar / processClose (the host is filling its orders). That bar is a confirmed history bar\n * (`barstate.isconfirmed`); `barstate.islast`, `last_bar_index` and `BarContext.n` keep the chart's last bar. Risk\n * rules are not declared again, and the outputs (plots, drawings) are dropped. Re-entrant: the host calls it inside\n * the bar loop of the main run.\n *\n * Resumed runs: the intrabar runs of a backtest (same recorder, script, inputs, chart and engine) keep the state of\n * the script as createScriptRun does, so a run calculates its bar only (and the bars since the previous intrabar run);\n * the order calls and `strategy.*` reads are the same as in a full run. The bars before `options.bar` must be the main\n * run's (the same on every call). A script that keeps state outside `persist()` boxes, or uses a feature that is not\n * resumed, gets full runs (`fullRunReason`); the first resumed runs are also calculated in full and compared\n * (`verify`). A resumed run gives its order calls to the engine once it has ended.\n * @param body - The script body, as given to executeScript().\n * @param bars - The bars up to and including the bar calculated inside, oldest first.\n * @param inputs - Input values by input id, as given to the main run.\n * @param chart - The chart context of the main run.\n * @param options - The bar, the chart's last bar index, the main run's engine and recorder, and the resume settings.\n * @returns The first bar calculated, whether the run was resumed, and why the runs are full ones (or null).\n */\nexport function executeIntrabar(\n body: () => void,\n bars: Bar[],\n inputs: Record<string, unknown>,\n chart: ChartContext,\n options: IntrabarOptions\n): IntrabarUpdate {\n const recorder = options.recorder;\n // History bars are confirmed, also on their ticks (the reference app: a barstate.isconfirmed entry fills on them).\n const runChart: ChartContext = { ...chart, lastBarConfirmed: true, realtime: false };\n const execute = (engine: StrategyEngine, inc: incremental.ActiveRun | null): void => {\n const run: IntrabarRun = { bar: options.bar, lastBarIndex: options.lastBarIndex, engine, recorder };\n runBody(\n () => {\n intrabarRun = run;\n varipRun = { slot: 0, recorder, mode: 'live', scratch: null };\n body();\n },\n bars,\n inputs,\n runChart,\n { strategyEngine: () => engine },\n inc\n );\n };\n const fullRun = (reason: string | null): IntrabarUpdate => {\n execute(options.engine, null);\n return { from: 0, incremental: false, fullRunReason: reason };\n };\n if (options.resume === false) return fullRun('resume: false');\n const n = bars.length;\n if (options.bar !== n - 1) return fullRun('the bar is not the last of the bars');\n\n let chain = intrabarChains.get(recorder);\n if (\n !chain || chain.body !== body || chain.engine !== options.engine || chain.lastBarIndex !== options.lastBarIndex ||\n !sameResult(chain.inputs, inputs) || !sameChart(chain.chart, runChart)\n ) {\n chain = {\n body,\n inputs,\n chart: runChart,\n engine: options.engine,\n lastBarIndex: options.lastBarIndex,\n memory: null,\n n: 0,\n reason: null,\n verifyLeft: options.verify ?? 2,\n };\n intrabarChains.set(recorder, chain);\n }\n if (chain.reason) return fullRun(chain.reason);\n\n const memory = chain.memory;\n // A resumed run changes the memory in place: it is usable again only when the run has ended.\n chain.memory = null;\n if (!memory || n < chain.n) {\n const inc = newActiveRun('record', bars, 0, null);\n execute(options.engine, inc);\n if (inc.blocked) chain.reason = inc.blocked;\n else {\n chain.memory = inc.next;\n chain.n = n;\n }\n return { from: 0, incremental: false, fullRunReason: chain.reason };\n }\n\n const from = chain.n - 1;\n const start = incremental.plainCopy(recorder.varip);\n if (start === incremental.NOT_COPIED) {\n chain.reason = 'a varip value that is not plain data';\n return fullRun(chain.reason);\n }\n const verifying = chain.verifyLeft > 0;\n const log: unknown[] | null = verifying ? [] : null;\n const writes: Array<() => void> = [];\n const inc = newActiveRun('resume', bars, from, memory);\n try {\n execute(intrabarEngine(options.engine, log, writes), inc);\n } catch (err) {\n // The run is calculated in full instead: the varip values back to the start, the kept order calls dropped. An\n // error of the script is the full run's (it throws it again).\n setVarip(recorder, start as unknown[]);\n if (err instanceof incremental.ResumeAborted) chain.reason = err.reason;\n return fullRun(chain.reason);\n }\n if (verifying) {\n chain.verifyLeft--;\n const resumedVarip = incremental.plainCopy(recorder.varip);\n setVarip(recorder, start as unknown[]);\n const fullLog: unknown[] = [];\n execute(intrabarEngine(options.engine, fullLog, null), null);\n if (resumedVarip === incremental.NOT_COPIED || !sameResult(log, fullLog) || !sameResult(resumedVarip, recorder.varip)) {\n chain.reason = 'a resumed intrabar run differs from a full run (state kept outside persist()?)';\n return { from: 0, incremental: false, fullRunReason: chain.reason };\n }\n } else {\n for (const call of writes) call();\n }\n chain.memory = inc.next;\n chain.n = n;\n return { from, incremental: true, fullRunReason: null };\n}\n\n/** The state of an incremental run: a recorded one (full), or one resumed at bar `from` from `prev`. */\nfunction newActiveRun(\n mode: 'record' | 'resume',\n b: Bar[],\n from: number,\n prev: incremental.RunMemory | null\n): incremental.ActiveRun {\n const next = incremental.emptyMemory(b.length);\n // the block that draws stays the one of the previous run (the forming bar may not draw)\n if (mode === 'resume' && prev) next.drawingBlock = prev.drawingBlock;\n return {\n mode,\n from,\n bars: b,\n prev: mode === 'resume' ? prev : null,\n next,\n seriesSlot: 0,\n taSlot: 0,\n blockSlot: 0,\n plotSlot: 0,\n boxSlot: 0,\n drawSlot: 0,\n block: -1,\n boxes: [],\n blocked: null,\n };\n}\n\n// \u2500\u2500 Incremental runs (#196) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The result of {@link ScriptRun.update}. */\nexport interface ScriptRunUpdate extends ScriptRunResult {\n /** First bar calculated: the forming bar of the previous update (a resumed run), or 0 (a full run) */\n from: number;\n /** The update was resumed from the state of the last confirmed bar */\n incremental: boolean;\n}\n\nexport interface ScriptRunOptions extends ScriptOptions {\n /**\n * Resumed updates also calculated in full and compared, the first ones of the run (default 2): a difference makes\n * the next updates full runs (a script that keeps state outside persist() boxes)\n */\n verify?: number;\n}\n\n/** A script calculated again on each update of the chart bars (see {@link createScriptRun}). */\nexport interface ScriptRun {\n /**\n * The script on `bars`: resumed from the forming bar of the previous update when the bars before it did not change\n * (a live update of the forming bar, or new bars after it), else a full run.\n */\n update(bars: Bar[], chart?: ChartContext): ScriptRunUpdate;\n /** Why the updates are full runs: a feature that is not resumed, or a verification difference (null: resumed) */\n readonly fullRunReason: string | null;\n}\n\n/** Chart context fields that only change the last bar (barstate of the forming bar). */\nconst LAST_BAR_FIELDS = new Set(['lastBarConfirmed', 'lastBarNew', 'realtime', 'now']);\n\n/** The visible range of the chart: part of the chart only for a script that reads it. */\nconst VISIBLE_RANGE_FIELDS = new Set(['leftVisibleBarTime', 'rightVisibleBarTime']);\n\nfunction sameChart(a: ChartContext, b: ChartContext, visibleRange = true): boolean {\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]);\n for (const k of keys) {\n if (LAST_BAR_FIELDS.has(k) || (!visibleRange && VISIBLE_RANGE_FIELDS.has(k))) continue;\n if (!Object.is((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) return false;\n }\n return true;\n}\n\n/** The bar values an update compares with the next one. */\ninterface BarsCopy {\n n: number;\n values: Float64Array;\n}\n\n/** `b` in `copy` from bar `from` on (the bars before are already there); a new copy when `copy` is null. */\nfunction copyBars(b: readonly Bar[], copy: BarsCopy | null = null, from = 0): BarsCopy {\n let values = copy?.values ?? new Float64Array(Math.max(16, b.length) * 6);\n if (values.length < b.length * 6) {\n const grown = new Float64Array(b.length * 12);\n grown.set(values.subarray(0, from * 6));\n values = grown;\n }\n for (let i = from; i < b.length; i++) {\n const x = b[i]!;\n const o = i * 6;\n values[o] = x.time as number;\n values[o + 1] = x.open;\n values[o + 2] = x.high;\n values[o + 3] = x.low;\n values[o + 4] = x.close;\n values[o + 5] = x.volume ?? NaN;\n }\n return { n: b.length, values };\n}\n\n/** a and b are the same number (NaN equal to NaN, -0 not 0) */\nconst sameNumber = (a: number, b: number): boolean => a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;\n\n/** The first `count` bars of `b` have the values of `copy`. */\nfunction sameBars(copy: BarsCopy, b: readonly Bar[], count: number): boolean {\n const v = copy.values;\n for (let i = 0; i < count; i++) {\n const x = b[i]!;\n const o = i * 6;\n if (\n !sameNumber(v[o]!, x.time as number) || !sameNumber(v[o + 1]!, x.open) || !sameNumber(v[o + 2]!, x.high) ||\n !sameNumber(v[o + 3]!, x.low) || !sameNumber(v[o + 4]!, x.close) || !sameNumber(v[o + 5]!, x.volume ?? NaN)\n ) {\n return false;\n }\n }\n return true;\n}\n\n/** Two run results with the same values (numbers compared with Object.is: NaN equal, -0 not 0). */\nfunction sameResult(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const ka = Object.keys(a);\n const kb = Object.keys(b);\n if (ka.length !== kb.length) return false;\n for (const k of ka) {\n if (!sameResult((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) return false;\n }\n return true;\n}\n\n/**\n * Host-side: a script that calculates only the newest bars on a live update. Scripts never call it. The first\n * update is a full run; it keeps,\n * for the next one, what the script created (its Series, ta.* calls, eachBar() blocks, persist() boxes and plots) with\n * their state at the end of the last confirmed bar. An update whose bars are the same up to the forming bar of the\n * previous update (a new price of the forming bar, or new bars after it) runs the script again from that bar only;\n * the result is the same as a full run on the same bars. Other changes (history loaded, inputs, symbol, timeframe or\n * other chart fields) run it in full.\n *\n * The state the script keeps from one bar to the next has to be in `persist()` boxes (not in `let` variables outside the\n * eachBar() callbacks, which a resumed run cannot put back). The first resumed updates are also calculated in full and\n * compared (`verify`): a difference makes the next updates full runs. Not resumed yet, so calculated in full: drawings,\n * request.security, strategies, varip, timenow, last_bar_index, BarContext.n, barstate.islastconfirmedhistory\n * (`fullRunReason` names the first one met).\n * @param body - The script body, a function that runs the script's statements.\n * @param inputs - Input values by input id. Default: `{}` (every input at its default).\n * @param chart - The chart context (timeframe, time zone, session, symbol...); an update can give a new one.\n * Default: `{}`.\n * @param options - The executeScript() options, plus `verify` (resumed updates also run in full and compared).\n * Default: `{}`.\n * @returns A run: call `update(bars, chart?)` on each change of the bars; `fullRunReason` says why it does not resume.\n */\nexport function createScriptRun(\n body: () => void,\n inputs: Record<string, unknown> = {},\n chart: ChartContext = {},\n options: ScriptRunOptions = {}\n): ScriptRun {\n let memory: incremental.RunMemory | null = null;\n let previous: BarsCopy | null = null;\n let previousChart: ChartContext = chart;\n let reason: string | null = null;\n let verifyLeft = options.verify ?? 2;\n /** A bar calculated so far read the visible range. */\n let rangeRead = false;\n /** The log messages of the last update: a resumed update keeps those of the bars it does not calculate again. */\n let lastLogs: LogEntry[] | undefined;\n\n const newRun = (mode: 'record' | 'resume', b: Bar[], from: number): incremental.ActiveRun =>\n newActiveRun(mode, b, from, memory);\n\n const full = (b: Bar[], c: ChartContext): ScriptRunUpdate => {\n memory = null;\n if (reason) return { ...runBody(body, b, inputs, c, options, null), from: 0, incremental: false };\n const inc = newRun('record', b, 0);\n const result = runBody(body, b, inputs, c, options, inc);\n if (inc.blocked) reason = inc.blocked;\n else memory = inc.next;\n return { ...result, from: 0, incremental: false };\n };\n\n return {\n get fullRunReason() {\n return reason;\n },\n update(b: Bar[], c: ChartContext = previousChart): ScriptRunUpdate {\n const last = previous;\n const m = memory;\n const resumable =\n !reason && m !== null && last !== null && last.n >= 1 && b.length >= last.n && sameChart(previousChart, c, rangeRead) &&\n sameBars(last, b, last.n - 1);\n previousChart = c;\n let out: ScriptRunUpdate;\n if (!resumable) {\n out = full(b, c);\n } else {\n const from = last!.n - 1;\n const inc = newRun('resume', b, from);\n let result: ScriptRunResult | null = null;\n try {\n result = runBody(body, b, inputs, c, options, inc);\n result.result.logs = resumedLogs(lastLogs, result.result.logs, from);\n result.usesVisibleRange ||= rangeRead;\n } catch (err) {\n // the memory is changed in place by a resumed run: an error leaves it unusable\n memory = null;\n previous = null;\n if (!(err instanceof incremental.ResumeAborted)) throw err;\n reason = err.reason;\n }\n if (result && verifyLeft > 0) {\n verifyLeft--;\n const check = runBody(body, b, inputs, c, options, null);\n check.usesVisibleRange = result.usesVisibleRange;\n if (!sameResult(result, check)) {\n reason = 'a resumed update differs from a full run (state kept outside persist()?)';\n result = check;\n }\n }\n if (result && !reason) {\n memory = inc.next;\n out = { ...result, from, incremental: true };\n } else {\n out = result && reason ? { ...result, from: 0, incremental: false } : full(b, c);\n memory = null;\n }\n }\n previous = out.incremental && last ? copyBars(b, last, last.n - 1) : copyBars(b);\n lastLogs = out.result.logs;\n rangeRead = out.usesVisibleRange;\n return out;\n },\n };\n}\n\n// \u2500\u2500 varip \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** How `varip` boxes read and write in the running code. */\ninterface VaripRun {\n /** Next slot (boxes are numbered in their call order in the script). */\n slot: number;\n recorder: StrategyRecorder | null;\n /** live: the recorder's current values; replay: the copy of a replayed bar's start values. */\n mode: 'live' | 'replay';\n scratch: unknown[] | null;\n}\nlet varipRun: VaripRun = { slot: 0, recorder: null, mode: 'live', scratch: null };\n\n/** A `varip` variable: `.value` reads and writes it. */\nexport interface VaripVariable<T> {\n /** The current value of the variable. */\n value: T;\n}\n\n/**\n * A strategy variable that keeps the changes made while a bar is calculated again inside the bar (on order fills or\n * ticks). A plain variable comes back to its value at the start of the bar on each of those runs; a `varip` one does\n * not, so it can count fills or ticks. Declare it once in the script body (outside the callbacks), in the same order\n * on each run; read and write `.value` in strategy.eachBar(). Without intrabar runs it is a plain variable.\n * @param initial - The starting value.\n * @returns A box whose `.value` reads and writes the variable.\n * @example\n * ```js\n * const updatesInTrade = varip(0);\n * strategy.eachBar((c) => {\n * if (strategy.position_size !== 0) updatesInTrade.value += 1;\n * });\n * ```\n */\nexport function varip<T>(initial: T): VaripVariable<T> {\n collector();\n // the intrabar runs of a backtest resume with varip values read in strategy.eachBar() (#206)\n if (!intrabarRun) incremental.nonIncremental('varip');\n const slot = varipRun.slot++;\n const state = varipRun;\n const rec = state.recorder;\n if (!rec) {\n let current = initial;\n return {\n get value() {\n return current;\n },\n set value(v: T) {\n current = v;\n },\n };\n }\n if (rec.varip.length <= slot) rec.varip[slot] = initial;\n const store = (): unknown[] => {\n // elsewhere, a resumed run would keep values of the bars before calculated with older varip values\n if (incremental.active && !ctx?.strategy?.inLoop) incremental.nonIncremental('varip used outside strategy.eachBar()');\n return state.mode === 'replay' && state.scratch ? state.scratch : rec.varip;\n };\n return {\n get value() {\n return store()[slot] as T;\n },\n set value(v: T) {\n store()[slot] = v;\n },\n };\n}\n\n// \u2500\u2500 persist \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** A `persist` variable: `.value` reads and writes it. */\nexport interface PersistVariable<T> {\n /** The current value of the variable. */\n value: T;\n}\n\n/**\n * A variable that keeps its value from one bar to the next, kept by the runtime. Declare it in the script body\n * (outside the callbacks), in the same order on each run, and read and write `.value` in one eachBar() callback. On a\n * live chart the runtime saves its value at the end of the last confirmed bar and puts it back before the forming bar\n * is calculated again, so only the newest bar is calculated: prefer it to a `let` variable outside the callback.\n * The script is calculated in full on each update (same results, slower) when the variable is used outside an\n * eachBar() callback, by two eachBar() blocks, or holds something else than plain data (numbers, strings, booleans,\n * arrays, plain objects, Map, Set). Calling it inside a bar loop throws.\n * @param initial - The value before the first bar.\n * @returns A box whose `.value` reads and writes the variable.\n * @example\n * ```js\n * const dir = persist(0);\n * const trend = eachBar((c) => {\n * if (c.close > c.get(close, 1)) dir.value = 1;\n * else if (c.close < c.get(close, 1)) dir.value = -1;\n * return dir.value;\n * });\n * ```\n */\nexport function persist<T>(initial: T): PersistVariable<T> {\n collector();\n if (currentBar >= 0) {\n throw new Error('persist() is declared in the script body, outside the eachBar() callback (once per run).');\n }\n let current = initial;\n const run = incremental.active;\n if (!run) {\n return {\n get value() {\n return current;\n },\n set value(v: T) {\n current = v;\n },\n };\n }\n const slot = run.boxSlot++;\n run.boxes[slot] = {\n get: () => current,\n set: (v) => {\n current = v as T;\n },\n };\n if (run.mode === 'resume') run.next.boxOwner[slot] = run.prev?.boxOwner[slot];\n const touch = (): void => {\n if (incremental.active !== run) return;\n if (run.block < 0) {\n incremental.nonIncremental('persist() used outside eachBar()');\n return;\n }\n const owner = run.next.boxOwner[slot];\n if (owner === undefined) run.next.boxOwner[slot] = run.block;\n else if (owner !== run.block) incremental.nonIncremental('persist() used by two eachBar() blocks');\n };\n return {\n get value() {\n touch();\n return current;\n },\n set value(v: T) {\n touch();\n current = v;\n },\n };\n}\n\n// \u2500\u2500 Declarations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Options of {@link indicator}. */\nexport interface IndicatorOptions {\n /** Short name shown in the chart legend. Default: the title. */\n shorttitle?: string;\n /** true: drawn on the price pane; false: in its own pane below the chart. Default: false. */\n overlay?: boolean;\n /** Number of decimals of the values shown in the legend and on the price scale. Default: the host's choice (the symbol's precision). */\n precision?: number;\n /** Number format of the values: `format.price`, `format.volume`, `format.percent`, `format.mintick` or `format.inherit`. Default: `format.inherit`. */\n format?: string;\n /** The price scale the script uses: `scale.right`, `scale.left` or `scale.none`. Default: the host's choice. */\n scale?: 'right' | 'left' | 'none';\n /** Most lines kept alive; above it the oldest are deleted (a few more may stay for a moment). Default: 50. */\n max_lines_count?: number;\n /** Most labels kept alive; above it the oldest are deleted. Default: 50. */\n max_labels_count?: number;\n /** Most boxes kept alive; above it the oldest are deleted. Default: 50. */\n max_boxes_count?: number;\n /** Most polylines kept alive; above it the oldest are deleted. Default: 50. */\n max_polylines_count?: number;\n /**\n * Where the script is drawn, instead of `overlay` (give one of the two): 'price' (on the price pane), 'separate'\n * (its own pane) or 'auto' (chosen from the plotted values: the price pane when they are prices, like an average;\n * its own pane otherwise, like an RSI). Default: not set (`overlay` decides).\n */\n pane?: 'price' | 'separate' | 'auto';\n}\n\n/**\n * Declares the script as an indicator: its title, its pane and how its values are shown. Call it once, at the top\n * of the script (a script declares either `indicator()` or `strategy()`). A script without a declaration runs with\n * the title \"Untitled\" in its own pane.\n * @param title - Name of the script, shown in the legend and the settings.\n * @param options - Pane, short title, number format and drawing limits. Default: `{}` (own pane).\n * @example\n * ```js\n * indicator(\"My SMA\", { overlay: true, precision: 2 });\n * plot(ta.sma(close, 20), \"SMA\");\n * ```\n */\nexport function indicator(title: string, options: IndicatorOptions = {}): void {\n const c = collector();\n declare(c, 'indicator');\n c.title = title;\n c.shortTitle = options.shorttitle;\n if (options.pane !== undefined) {\n if (!['price', 'separate', 'auto'].includes(options.pane)) {\n throw new ScriptError(`indicator(): pane is 'price', 'separate' or 'auto', got ${shown(options.pane)}.`);\n }\n if (options.overlay !== undefined) throw new ScriptError('indicator(): give overlay or pane, not both.');\n }\n c.overlay = options.pane === 'price' ? true : options.pane === undefined ? (options.overlay ?? false) : false;\n c.paneAuto = options.pane === 'auto';\n c.pane = options.pane;\n c.precision = options.precision;\n c.format = options.format;\n c.scale = options.scale;\n setDrawingLimits({\n line: options.max_lines_count,\n label: options.max_labels_count,\n box: options.max_boxes_count,\n polyline: options.max_polylines_count,\n });\n}\n\nfunction declare(c: Collector, kind: 'indicator' | 'strategy'): void {\n if (c.declaration) {\n throw new Error(`${kind}(): the script already declared ${c.declaration}(); a script has one declaration.`);\n }\n c.declaration = kind;\n}\n\n/** Options of every `input.*` kind: where the input is listed in the settings and how it behaves. */\nexport interface InputOptions {\n /** Group title: every input with the same `group` is listed under it, at the place of the group's first input. Default: no group. */\n group?: string;\n /** Inputs with the same `inline` id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own. */\n inline?: string;\n /** Help text shown next to the input. Default: none. */\n tooltip?: string;\n /** true: the host asks for the value when the script is added to a chart. Default: false. */\n confirm?: boolean;\n /**\n * Where the value is shown besides the settings: `display.all`, `display.none`, `display.status_line` or\n * `display.data_window`. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.\n */\n display?: InputConfig['display'];\n /**\n * false greys the input out in the settings (it keeps its value). A boolean (`active: showMa`), or a condition on\n * input ids that a host can apply without running the script (`active: 'ma_1'`,\n * `active: { input: 'type', ne: 'None' }`). Default: true.\n */\n active?: boolean | InputCondition;\n /**\n * The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made\n * from the title (\"Fast length\" gives fast_length), which changes when the title changes.\n */\n id?: string;\n}\n\n/** Options of `input.int()` and `input.float()`. */\nexport interface NumericInputOptions extends InputOptions {\n /** Smallest value the user can enter. Default: no minimum. */\n minval?: number;\n /** Largest value the user can enter. Default: no maximum. */\n maxval?: number;\n /** Step of the arrows of the number field. Default: the host's choice (1 for an int). */\n step?: number;\n /** The values to choose from (the host shows a drop-down list). Default: a free number field. */\n options?: number[];\n}\n\n/** A field of an enum made with `defineEnum()`: its name and title. `String(field)` is the title. */\nexport interface EnumField {\n /** The field's name, as written in `defineEnum()` (`\"sma\"`). */\n readonly name: string;\n /** The field's title, shown in the settings (`\"Simple\"`); the name when the title was empty. */\n readonly title: string;\n /** The title, so `String(field)` and `str.tostring(field)` give it. */\n toString(): string;\n}\n\n/** Options of `input.enum()`. */\nexport interface EnumInputOptions extends InputOptions {\n /** The fields to choose from, all of the default's enum. Default: every field of the enum. */\n options?: EnumField[];\n}\n\n/** A class, not a plain object: a field passed where the options can be is not read as named arguments. */\nclass EnumFieldValue implements EnumField {\n constructor(readonly name: string, readonly title: string) {\n Object.freeze(this);\n }\n toString(): string {\n return this.title;\n }\n}\n\n/** The fields of each enum, by field: `input.enum()` lists them from its default. */\nconst enumFieldsOf = new WeakMap<EnumField, readonly EnumField[]>();\n\n/**\n * Makes an enum: a fixed set of named fields, each with a title, for a choice list (`input.enum()`) or a state with\n * a few values. Fields compare with `===`; `field.name` is the name, `field.title` and `String(field)` the title.\n * @param fields - An object of field names and titles, e.g. `{ sma: \"Simple\", ema: \"Exponential\" }`; an empty title\n * is the name.\n * @returns A frozen object with one {@link EnumField} per name.\n * @example\n * ```js\n * const MaType = defineEnum({ sma: \"Simple\", ema: \"Exponential\" });\n * const maType = input.enum(MaType.sma, \"Average\");\n * plot(maType === MaType.ema ? ta.ema(close, 20) : ta.sma(close, 20), \"MA\");\n * ```\n */\nexport function defineEnum<K extends string>(fields: Record<K, string>): { readonly [P in K]: EnumField } {\n if (!isPlainObject(fields) || Object.keys(fields).length === 0) {\n throw new TypeError('defineEnum(): the fields are an object of names and titles, e.g. { sma: \"Simple\", ema: \"Exponential\" }.');\n }\n const list: EnumField[] = [];\n const out: Record<string, EnumField> = {};\n for (const [name, title] of Object.entries(fields)) {\n if (title !== undefined && typeof title !== 'string') throw new TypeError(`defineEnum(): the title of \"${name}\" is a string.`);\n const field = new EnumFieldValue(name, title || name);\n list.push(field);\n out[name] = field;\n }\n for (const field of list) enumFieldsOf.set(field, list);\n return Object.freeze(out) as { readonly [P in K]: EnumField };\n}\n\n/** Options of `input.string()`, `input.timeframe()`, `input.session()` and `input.symbol()`. */\nexport interface StringInputOptions extends InputOptions {\n /** The values to choose from (the host shows a drop-down list). Default: a free text field (or the kind's own picker). */\n options?: string[];\n}\n\n/** The InputConfig fields of the common input options (unset options are left out). */\nfunction common(opts: InputOptions): Partial<InputConfig> {\n const out: Partial<InputConfig> = {};\n if (opts.group !== undefined) out.group = opts.group;\n if (opts.inline !== undefined) out.inline = opts.inline;\n if (opts.tooltip !== undefined) out.tooltip = opts.tooltip;\n if (opts.confirm !== undefined) out.confirm = opts.confirm;\n if (opts.display !== undefined) out.display = opts.display;\n if (opts.active !== undefined) out.active = opts.active;\n if (opts.id !== undefined) out.id = opts.id;\n return out;\n}\n\n/** Declares the input in the collector and returns its current value (the\n * host-supplied override when present, else the default). */\nfunction registerInput<T>(config: Omit<InputConfig, 'id'>, fallbackId: string): T {\n const c = collector();\n const wanted = (config as Partial<InputConfig>).id;\n let id: string;\n if (wanted !== undefined) {\n if (typeof wanted !== 'string' || !/^[A-Za-z_]\\w*$/.test(wanted)) {\n throw new ScriptError(`input id ${shown(wanted)}: letters, digits and _ only, not starting with a digit, e.g. \"fast_length\".`);\n }\n if (c.inputIds.has(wanted)) throw new ScriptError(`Two inputs have the id \"${wanted}\": give each its own.`);\n c.inputIds.add(wanted);\n id = wanted;\n } else {\n id = slugId(config.title, fallbackId, c.inputIds);\n }\n c.inputConfig.push({ ...config, id });\n c.defaultInputs[id] = config.defval;\n const value = c.inputValues[id];\n if (c.strict && value !== undefined) checkInputValue({ id, ...config }, id, value);\n return (value === undefined ? config.defval : value) as T;\n}\n\n/** `idKind`: the kind in the id of an input without title (a price input keeps the ids of the float input it was). */\nfunction registerNumeric(type: 'int' | 'float' | 'price', defval: number, title?: string, opts: NumericInputOptions = {}, idKind: string = type): number {\n const v = registerInput<unknown>(\n { type, defval, title, min: opts.minval, max: opts.maxval, step: opts.step, ...(opts.options ? { options: opts.options } : {}), ...common(opts) },\n `input_${idKind}`\n );\n return typeof v === 'number' ? v : defval;\n}\n\n/** Named arguments of an input: its options, with `title` (and `defval` when every argument is named). */\ntype InputArgs<O, D> = O & { title?: string; defval?: D };\n\nconst COMMON_INPUT_KEYS = ['tooltip', 'inline', 'group', 'confirm', 'display', 'active', 'id'] as const;\n/** The PineScript arguments of each input kind (named arguments are checked against them). */\nconst INPUT_KEYS: Record<string, readonly string[]> = {\n int: ['defval', 'title', 'minval', 'maxval', 'step', 'options', ...COMMON_INPUT_KEYS],\n float: ['defval', 'title', 'minval', 'maxval', 'step', 'options', ...COMMON_INPUT_KEYS],\n enum: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],\n price: ['defval', 'title', ...COMMON_INPUT_KEYS],\n bool: ['defval', 'title', ...COMMON_INPUT_KEYS],\n string: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],\n text_area: ['defval', 'title', ...COMMON_INPUT_KEYS],\n color: ['defval', 'title', ...COMMON_INPUT_KEYS],\n source: ['defval', 'title', ...COMMON_INPUT_KEYS],\n timeframe: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],\n session: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],\n symbol: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],\n time: ['defval', 'title', ...COMMON_INPUT_KEYS],\n};\n\n/**\n * The default, title and options of an `input.*` call, as PineScript writes it: `(defval, title, options)`,\n * `(defval, { title, ...options })` or every argument by name (`{ defval, title, ...options }`). An unknown named\n * argument throws with the closest names (`min` for `minval`).\n */\nfunction inputArgs<D, O extends object>(\n kind: string,\n defvalOrArgs: unknown,\n titleOrArgs: unknown,\n opts: O | undefined\n): { defval: D; title: string | undefined; opts: O } {\n const name = `input.${kind}`;\n const keys = INPUT_KEYS[kind]!;\n let named: Record<string, unknown> = {};\n let defval = defvalOrArgs;\n let title: unknown = titleOrArgs;\n if (isPlainObject(defvalOrArgs)) {\n named = { ...defvalOrArgs };\n defval = named.defval;\n title = undefined;\n } else if (isPlainObject(titleOrArgs)) {\n named = { ...titleOrArgs };\n title = undefined;\n }\n if (opts !== undefined) {\n if (!isPlainObject(opts)) throw new TypeError(`${name}(): the options are an object, e.g. { tooltip: \"...\" }.`);\n named = { ...named, ...opts };\n }\n for (const key of Object.keys(named)) if (!keys.includes(key)) throw unknownArgument(name, key, keys);\n if (title !== undefined && typeof title !== 'string') {\n throw new TypeError(`${name}(): the title is a string, got ${typeof title}.`);\n }\n const { defval: namedDefval, title: namedTitle, ...rest } = named;\n return {\n defval: (defval ?? namedDefval) as D,\n title: (title as string | undefined) ?? (namedTitle as string | undefined),\n opts: rest as O,\n };\n}\n\n/**\n * Script inputs: each `input.*` call declares a setting the user can change AND returns its current value (the\n * user's value when there is one, else the default). The arguments after the default can be named:\n * `input.int(14, \"Length\", { minval: 1 })`, `input.int(14, { title: \"Length\", minval: 1 })` or\n * `input.int({ defval: 14, title: \"Length\" })`. The input id is the title in snake case (\"Fast length\" is\n * `fast_length`); keep titles stable, a renamed input loses the user's value.\n */\nexport const input = strictNamespace('input', {\n /**\n * Declares a whole-number setting (a length, a count) and returns its value, rounded to an integer.\n * @param defval - Default value, or every argument by name (`{ defval, title, minval... }`).\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_int`).\n * @param opts - `minval`, `maxval`, `step`, `options` (a choice list) and the common input options.\n * @returns The current value: the user's value, else `defval`.\n * @example\n * ```js\n * const length = input.int(14, \"Length\", { minval: 1, maxval: 500 });\n * plot(ta.rsi(close, length), \"RSI\");\n * ```\n */\n int(defval: number | InputArgs<NumericInputOptions, number>, title?: string | InputArgs<NumericInputOptions, number>, opts?: NumericInputOptions): number {\n const a = inputArgs<number, NumericInputOptions>('int', defval, title, opts);\n return Math.round(registerNumeric('int', a.defval, a.title, a.opts));\n },\n /**\n * Declares a decimal-number setting (a multiplier, a percent, a level) and returns its value.\n * @param defval - Default value, or every argument by name (`{ defval, title, minval... }`).\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_float`).\n * @param opts - `minval`, `maxval`, `step`, `options` (a choice list) and the common input options.\n * @returns The current value: the user's value, else `defval`.\n * @example\n * ```js\n * const mult = input.float(2.0, \"Multiplier\", { minval: 0.1, step: 0.1 });\n * const [basis, upper, lower] = ta.bb(close, 20, mult);\n * ```\n */\n float(defval: number | InputArgs<NumericInputOptions, number>, title?: string | InputArgs<NumericInputOptions, number>, opts?: NumericInputOptions): number {\n const a = inputArgs<number, NumericInputOptions>('float', defval, title, opts);\n return registerNumeric('float', a.defval, a.title, a.opts);\n },\n /**\n * Declares an on / off setting (a checkbox) and returns its value. Shown only in the settings by default.\n * @param defval - Default value, or every argument by name (`{ defval, title... }`).\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_bool`).\n * @param opts - The common input options (`group`, `inline`, `tooltip`, `confirm`, `display`, `active`, `id`).\n * @returns The current value: the user's value, else `defval`.\n * @example\n * ```js\n * const showMa = input.bool(true, \"Show MA\");\n * plot(ta.sma(close, 20), \"MA\", { display: showMa ? display.all : display.none });\n * ```\n */\n bool(defval: boolean | InputArgs<InputOptions, boolean>, title?: string | InputArgs<InputOptions, boolean>, opts?: InputOptions): boolean {\n const a = inputArgs<boolean, InputOptions>('bool', defval, title, opts);\n return registerInput<boolean>({ type: 'bool', defval: a.defval, title: a.title, ...common(a.opts) }, 'input_bool');\n },\n /**\n * Declares a text setting and returns its value; with `options`, a drop-down list of choices.\n * @param defval - Default value (one of `options` when they are given), or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_string`).\n * @param opts - `options` (a choice list) and the common input options.\n * @returns The current value: the user's value, else `defval`.\n * @example\n * ```js\n * const maType = input.string(\"EMA\", \"MA type\", { options: [\"SMA\", \"EMA\"] });\n * const ma = maType === \"SMA\" ? ta.sma(close, 20) : ta.ema(close, 20);\n * ```\n */\n string(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string {\n const a = inputArgs<string, StringInputOptions>('string', defval, title, opts);\n return registerInput<string>({ type: 'string', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_string');\n },\n /**\n * Declares a multi-line text setting (lines separated by a newline) and returns its value, e.g. a list of levels\n * the script parses. Shown only in the settings by default.\n * @param defval - Default text, or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_text_area`).\n * @param opts - The common input options.\n * @returns The current text: the user's text, else `defval`.\n * @example\n * ```js\n * const text = input.text_area(\"100\\n105\\n110\", \"Levels\");\n * for (const lvl of text.split(\"\\n\")) hline(Number(lvl), \"Level \" + lvl);\n * ```\n */\n text_area(defval: string | InputArgs<InputOptions, string>, title?: string | InputArgs<InputOptions, string>, opts?: InputOptions): string {\n const a = inputArgs<string, InputOptions>('text_area', defval, title, opts);\n return registerInput<string>({ type: 'text_area', defval: a.defval, title: a.title, ...common(a.opts) }, 'input_text_area');\n },\n /**\n * Declares a colour setting (a colour picker) and returns its value. The default's transparency is kept to 2\n * decimals (`color.new(c, 90)` gives the alpha byte 26); a value given by the host is used as it is. Shown only in\n * the settings by default.\n * @param defval - Default colour (`color.blue`, `\"#2962FF\"`, `color.new(...)`), or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_color`).\n * @param opts - The common input options.\n * @returns The current colour string: the user's colour, else `defval`.\n * @example\n * ```js\n * const lineColor = input.color(color.teal, \"Line colour\");\n * plot(ta.ema(close, 20), \"EMA\", { color: lineColor });\n * ```\n */\n color(defval: string | InputArgs<InputOptions, string>, title?: string | InputArgs<InputOptions, string>, opts?: InputOptions): string {\n const a = inputArgs<string, InputOptions>('color', defval, title, opts);\n return registerInput<string>({ type: 'color', defval: inputColorDefault(a.defval), title: a.title, ...common(a.opts) }, 'input_color');\n },\n /**\n * Declares a source setting (the price a calculation reads) and returns it as a Series. The choices are `open`,\n * `high`, `low`, `close`, `volume`, `hl2`, `hlc3`, `ohlc4`, `hlcc4`, and the outputs of other scripts on the chart\n * when the host allows it (an unknown source gives `close`).\n * @param defval - Default source, by name (`\"close\"`) or as the built-in Series (`close`), or every argument by\n * name. Default: `\"close\"`.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_source`).\n * @param opts - The common input options.\n * @returns The chosen source as a Series.\n * @example\n * ```js\n * const src = input.source(close, \"Source\");\n * plot(ta.sma(src, 20), \"SMA\");\n * ```\n */\n source(defval: string | Series = 'close', title?: string | InputArgs<InputOptions, string | Series>, opts?: InputOptions): Series {\n const a = inputArgs<string | Series, InputOptions>('source', defval, title, opts);\n const name = registerInput<string>({ type: 'source', defval: sourceName(a.defval ?? 'close'), title: a.title, ...common(a.opts) }, 'input_source');\n return sourceSeries(name);\n },\n /**\n * Declares a timeframe setting (a timeframe picker) and returns its value, for `request.security()` or\n * `timeframe.change()`.\n * @param defval - Default timeframe: `\"60\"` (60 minutes), `\"D\"`, `\"W\"`, `\"M\"`...; `\"\"` is the chart's timeframe.\n * Or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_timeframe`).\n * @param opts - `options` (a choice list of timeframes) and the common input options.\n * @returns The current timeframe string (`\"\"`: the chart's timeframe).\n * @example\n * ```js\n * const tf = input.timeframe(\"D\", \"Higher timeframe\");\n * const htfClose = request.security(\"\", tf, () => close);\n * ```\n */\n timeframe(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string {\n const a = inputArgs<string, StringInputOptions>('timeframe', defval, title, opts);\n return registerInput<string>({ type: 'timeframe', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_timeframe');\n },\n /**\n * Declares a trading-hours setting and returns its value, a session string for `time()` or `inSession()`.\n * @param defval - Default session: `\"HHMM-HHMM\"`, optionally followed by `:` and the days (1 = Sunday ...\n * 7 = Saturday), e.g. `\"0930-1600\"` or `\"0930-1600:23456\"`. Or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_session`).\n * @param opts - `options` (a choice list of sessions) and the common input options.\n * @returns The current session string.\n * @example\n * ```js\n * const sess = input.session(\"0930-1600\", \"Session\");\n * bgcolor(color.when(na(time(\"\", sess)).not(), color.new(color.blue, 90)));\n * ```\n */\n session(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string {\n const a = inputArgs<string, StringInputOptions>('session', defval, title, opts);\n return registerInput<string>({ type: 'session', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_session');\n },\n /**\n * Declares a symbol setting (a symbol search) and returns its value, a ticker id for `request.security()` of\n * another symbol.\n * @param defval - Default ticker id, `\"EXCHANGE:TICKER\"` (`\"NASDAQ:MSFT\"`), or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_symbol`).\n * @param opts - `options` (a choice list of symbols) and the common input options.\n * @returns The current ticker id.\n * @example\n * ```js\n * const other = input.symbol(\"NASDAQ:MSFT\", \"Compare with\");\n * plot(request.security(other, \"\", () => close), \"Other close\");\n * ```\n */\n symbol(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string {\n const a = inputArgs<string, StringInputOptions>('symbol', defval, title, opts);\n return registerInput<string>({ type: 'symbol', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_symbol');\n },\n /**\n * Declares a price-level setting (a number field) and returns its value. With `confirm: true` the host can ask the\n * user to pick it on the chart; an `inline` id shared with an `input.time()` makes one chart point of both.\n * @param defval - Default price, or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_float`).\n * @param opts - The common input options.\n * @returns The current price: the user's value, else `defval`.\n * @example\n * ```js\n * const level = input.price(100, \"Level\", { confirm: true });\n * hline(level, \"Level\");\n * ```\n */\n price(defval: number | InputArgs<InputOptions, number>, title?: string | InputArgs<InputOptions, number>, opts?: InputOptions): number {\n const a = inputArgs<number, InputOptions>('price', defval, title, opts);\n return registerNumeric('price', a.defval, a.title, a.opts, 'float');\n },\n /**\n * Declares a choice among the fields of an enum made with `defineEnum()` and returns the chosen field. The\n * settings list the fields by title; the host stores the field's name.\n * @param defval - Default field (`MaType.sma`), or every argument by name. It must be one of `options`.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_enum`).\n * @param opts - `options` (only these fields of the enum) and the common input options.\n * @returns The chosen field; compare it with `===`.\n * @example\n * ```js\n * const MaType = defineEnum({ sma: \"Simple\", ema: \"Exponential\" });\n * const maType = input.enum(MaType.sma, \"Average\");\n * const ma = maType === MaType.ema ? ta.ema(close, 20) : ta.sma(close, 20);\n * ```\n */\n enum<F extends EnumField>(defval: F | InputArgs<EnumInputOptions, F>, title?: string | InputArgs<EnumInputOptions, F>, opts?: EnumInputOptions): F {\n const a = inputArgs<F, EnumInputOptions>('enum', defval, title, opts);\n const fields = a.defval === undefined ? undefined : enumFieldsOf.get(a.defval);\n if (!fields) throw new TypeError('input.enum(): the default is a field of an enum made with defineEnum(), e.g. input.enum(MaType.sma, \"Average\").');\n const choices = a.opts.options ?? fields;\n for (const f of choices) {\n if (!fields.includes(f)) throw new TypeError('input.enum(): the options are fields of the enum of the default.');\n }\n if (!choices.includes(a.defval)) throw new TypeError('input.enum(): the default is one of the options.');\n const name = registerInput<unknown>(\n {\n type: 'enum',\n defval: a.defval.name,\n title: a.title,\n options: choices.map((f) => f.name),\n optionsTitles: Object.fromEntries(choices.map((f) => [f.name, f.title])),\n ...common(a.opts),\n },\n 'input_enum'\n );\n return (choices.find((f) => f.name === name) ?? a.defval) as F;\n },\n /**\n * Declares a date-and-time setting and returns it as a UNIX time in milliseconds. With `confirm: true` the host\n * can ask the user to pick it on the chart. Shown only in the settings by default.\n * @param defval - Default time in ms, usually from `timestamp()`, or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_time`).\n * @param opts - The common input options.\n * @returns The current time in ms: the user's value, else `defval`.\n * @example\n * ```js\n * const start = input.time(timestamp(\"2024-01-01\"), \"Start\");\n * bgcolor(color.when(time.gte(start), color.new(color.green, 90)));\n * ```\n */\n time(defval: number | InputArgs<InputOptions, number>, title?: string | InputArgs<InputOptions, number>, opts?: InputOptions): number {\n const a = inputArgs<number, InputOptions>('time', defval, title, opts);\n const v = registerInput<unknown>({ type: 'time', defval: a.defval, title: a.title, ...common(a.opts) }, 'input_time');\n return typeof v === 'number' ? v : a.defval;\n },\n});\n\n// \u2500\u2500 OHLCV builtins \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Opening price of each bar, as a Series. In a bar loop, `c.open` is the value of the current bar.\n * @example\n * ```js\n * const body = close.sub(open);\n * plot(body, \"Body\", { style: plot.style_columns });\n * ```\n */\nexport const open = Series.fromBars(ctxBars, 'open');\n/**\n * Highest price of each bar, as a Series. In a bar loop, `c.high` is the value of the current bar.\n * @example\n * ```js\n * plot(ta.highest(high, 20), \"20-bar high\");\n * ```\n */\nexport const high = Series.fromBars(ctxBars, 'high');\n/**\n * Lowest price of each bar, as a Series. In a bar loop, `c.low` is the value of the current bar.\n * @example\n * ```js\n * plot(ta.lowest(low, 20), \"20-bar low\");\n * ```\n */\nexport const low = Series.fromBars(ctxBars, 'low');\n/**\n * Closing price of each bar, as a Series (on the forming bar, the latest price). The usual source of indicators.\n * In a bar loop, `c.close` is the value of the current bar.\n * @example\n * ```js\n * plot(ta.sma(close, 20), \"SMA\");\n * ```\n */\nexport const close = Series.fromBars(ctxBars, 'close');\n/**\n * Traded volume of each bar, as a Series (NaN when the data has no volume). In a bar loop, `c.volume`.\n * @example\n * ```js\n * plot(volume, \"Volume\", { style: plot.style_columns });\n * ```\n */\nexport const volume = Series.fromBars(ctxBars, 'volume');\n/**\n * Median price of each bar, (high + low) / 2, as a Series.\n * @example\n * ```js\n * plot(ta.sma(hl2, 10), \"Median SMA\");\n * ```\n */\nexport const hl2 = new Series(ctxBars, (b) => (b.high + b.low) / 2);\n/**\n * Typical price of each bar, (high + low + close) / 3, as a Series.\n * @example\n * ```js\n * plot(ta.sma(hlc3, 20), \"Typical SMA\");\n * ```\n */\nexport const hlc3 = new Series(ctxBars, (b) => (b.high + b.low + b.close) / 3);\n/**\n * Average price of each bar, (open + high + low + close) / 4, as a Series.\n * @example\n * ```js\n * plot(ohlc4, \"OHLC average\");\n * ```\n */\nexport const ohlc4 = new Series(ctxBars, (b) => (b.open + b.high + b.low + b.close) / 4);\n/**\n * Weighted close of each bar, (high + low + close + close) / 4, as a Series.\n * @example\n * ```js\n * plot(ta.ema(hlcc4, 20), \"Weighted close EMA\");\n * ```\n */\nexport const hlcc4 = new Series(ctxBars, (b) => (b.high + b.low + 2 * b.close) / 4);\n/**\n * Index of each bar, as a Series: 0 on the oldest bar, then 1, 2... In a bar loop, `c.i` is the same number.\n * @example\n * ```js\n * plotshape(bar_index.mod(10).eq(0), \"Every 10 bars\", { style: shape.circle });\n * ```\n */\nexport const bar_index = new Series(ctxBars, (_b, i) => i);\nbar_index.fullHistory = true;\n/**\n * Index of the last bar of the chart, the same on every bar, as a Series. In a bar loop, `c.n - 1`.\n * @example\n * ```js\n * bgcolor(color.when(bar_index.gte(last_bar_index.sub(9)), color.new(color.blue, 90)), { title: \"Last 10 bars\" });\n * ```\n */\nexport const last_bar_index = new Series(ctxBars, (_b, _i, data) => {\n // the same value on every bar, changed by a new bar: not kept by an incremental run (#196), but the same in the\n // intrabar runs of a backtest (the chart's last bar, #206)\n if (!intrabarRun) incremental.nonIncremental('last_bar_index');\n return chartBarCount(data.length) - 1;\n});\nlast_bar_index.fullHistory = true;\n// built-in price variables keep the whole history (no 5000-bar limit)\nfor (const s of [hl2, hlc3, ohlc4, hlcc4]) s.fullHistory = true;\n\nconst SOURCES: Record<string, Series> = { open, high, low, close, volume, hl2, hlc3, ohlc4, hlcc4 };\n\n/** The name of a source default: `input.source(close)` as `input.source(\"close\")` (PineScript passes the series). */\nfunction sourceName(defval: string | Series): string {\n if (typeof defval === 'string') return defval;\n const name = Object.keys(SOURCES).find((k) => SOURCES[k] === defval);\n if (!name) {\n throw new Error('input.source(): the default must be a built-in source (open, high, low, close, volume, hl2, hlc3, ohlc4, hlcc4).');\n }\n return name;\n}\n\nfunction sourceSeries(name: string): Series {\n const builtin = SOURCES[name];\n if (builtin) return builtin;\n // Another source (study on study): its values as the host gives them now, aligned with the bars.\n const ext = externalSource(name);\n if (!ext) return close;\n const values = Array.from(ext);\n return new Series(ctxBars, (_bar, i) => values[i] ?? NaN);\n}\n\n// \u2500\u2500 Bound ta namespace \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst bars = (): Bar[] => ctxBars.bars;\n\n/** A Series bound to the context bars whose values come from one pass over all bars\n * (cumulative indicators), recomputed when the bars version changes. */\nfunction barsSeries(compute: (b: Bar[]) => Series): Series {\n let version = -1;\n let values: number[] = [];\n return new Series(ctxBars, (_bar, i, data) => {\n if (version !== ctxBars.version) {\n values = compute(data).toArray();\n version = ctxBars.version;\n }\n return values[i] ?? NaN;\n });\n}\n\n// \u2500\u2500 Guards for script mistakes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Edit distance of two names (for the \"did you mean\" of a namespace). */\nfunction editDistance(a: string, b: string): number {\n const row = Array.from({ length: b.length + 1 }, (_, j) => j);\n for (let i = 1; i <= a.length; i++) {\n let diag = row[0]!;\n row[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const up = row[j]!;\n row[j] = Math.min(up + 1, row[j - 1]! + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));\n diag = up;\n }\n }\n return row[b.length]!;\n}\n\n/** Names a tool reads to probe an object (promise, JSON, test matchers, module interop): never an error. */\nconst PROBED_NAMES = new Set(['then', 'toJSON', 'asymmetricMatch', 'nodeType', 'tagName', 'inspect', 'default']);\n\n/**\n * Compile-time check that a namespace's documented interface lists exactly the members of its implementation: a\n * member added to one but not the other makes the call fail to type-check (the argument becomes `false`).\n */\nfunction sameKeys<A, B>(_same: [Exclude<keyof A, keyof B>, Exclude<keyof B, keyof A>] extends [never, never] ? true : false): void {}\n\n/**\n * A namespace whose unknown members throw instead of being `undefined`: `ta.smaa(close, 5)` fails with\n * \"ta.smaa does not exist. Did you mean ta.sma?\" rather than \"ta.smaa is not a function\", and `color.purpel`\n * fails where it is read rather than giving a plot with no colour.\n */\nfunction strictNamespace<T extends object>(name: string, members: T): T {\n return new Proxy(members, {\n get(target, prop, receiver) {\n if (typeof prop === 'symbol' || prop in target || PROBED_NAMES.has(prop) || /^[_$@]/.test(prop)) {\n return Reflect.get(target, prop, receiver);\n }\n const keys = Object.keys(target);\n const lower = prop.toLowerCase();\n const ranked = keys\n .map((k) => ({ k, d: editDistance(lower, k.toLowerCase()) }))\n .filter(({ k, d }) => {\n const key = k.toLowerCase();\n return d <= Math.max(1, Math.floor(prop.length / 3)) || key.includes(lower) || (key.length >= 3 && lower.includes(key));\n })\n .sort((x, y) => x.d - y.d)\n .slice(0, 3)\n .map(({ k }) => `${name}.${k}`);\n throw new TypeError(\n `${name}.${prop} does not exist.` + (ranked.length ? ` Did you mean ${ranked.join(', ')}?` : '') +\n ' See docs/inventory.md for the supported functions.'\n );\n },\n });\n}\n\n/**\n * The ta.* functions compute a whole Series in one call. Called inside an eachBar() callback, a call runs again on\n * every bar (slow) and returns a Series, not the value of the bar, and it has no per-bar history: the call throws\n * with the fix.\n */\nfunction outsideBarLoops<T extends Record<string, unknown>>(members: T, ns = 'ta'): T {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(members)) {\n if (typeof value !== 'function') {\n out[key] = value;\n continue;\n }\n const fn = value as (...args: unknown[]) => unknown;\n out[key] = function (this: unknown, ...args: unknown[]) {\n if (currentBar >= 0) {\n throw new Error(\n `${ns}.${key}() was called inside eachBar(): a ${ns}.* call computes the whole Series at once. ` +\n `Compute it before the loop (const x = ${ns}.${key}(...)) and read the bar's value with c.get(x). ` +\n 'For a Pine ta.* call inside an if block or a for loop, use the callsite.* call sites.'\n );\n }\n return fn.apply(this, args);\n };\n }\n return out as T;\n}\n\n/**\n * A ta.* call of the script that has a {@link taStep} machine (#196). Outside an incremental run, the array function\n * (`full`). In an incremental run, the machine steps every bar of a recorded run, and only the bars from the forming bar\n * of the previous run in a resumed one (the machine holds the state of the last confirmed bar): the same doubles\n * (tests/ta/step.test.ts).\n */\nfunction stepped<R>(\n kind: string,\n make: () => BarStep<never[], unknown>,\n sources: Series[],\n args: (values: number[][], i: number) => unknown[],\n outs: number,\n full: () => R\n): R {\n const run = incremental.active;\n if (!run) return full();\n const slot = run.taSlot++;\n const b = sources[0] ? (sources[0].bars as Bar[]) : bars();\n const n = b.length;\n const values = sources.map((s) => s.toArray());\n let mem: incremental.TaMemory;\n let from = 0;\n const prev = run.mode === 'resume' ? run.prev?.ta[slot] : undefined;\n if (run.mode === 'resume') {\n if (!prev || prev.kind !== kind) incremental.nonIncremental(`a new ta.${kind}() call`);\n from = run.from;\n // the arrays of the previous run are the run's own: their first values are kept in place\n mem = { kind, machine: prev!.machine, outs: prev!.outs };\n } else {\n mem = { kind, machine: make() as BarStep<unknown[], unknown>, outs: Array.from({ length: outs }, () => []) };\n }\n for (const o of mem.outs) o.length = n;\n for (let i = from; i < n; i++) {\n const r = mem.machine.step(...args(values, i));\n if (outs === 1) mem.outs[0]![i] = typeof r === 'boolean' ? (r ? 1 : 0) : (r as number);\n else for (let k = 0; k < outs; k++) mem.outs[k]![i] = (r as number[])[k]!;\n // the forming bar is not committed: the next update steps it again from the confirmed bars\n if (i < n - 1) mem.machine.commit();\n }\n run.next.ta[slot] = mem;\n const series = mem.outs.map((o) => Series.fromArray(b, o));\n return (outs === 1 ? series[0] : series) as R;\n}\n\nconst at = (v: number[][], k: number, i: number): number => v[k]![i]!;\n\n/** The ta.* calls computed bar by bar in an incremental run (a length given as a Series uses the array function). */\nconst steppedTa = {\n sma: (source: Series, length: number | Series): Series =>\n typeof length === 'number'\n ? stepped('sma', taStep.sma, [source], (v, i) => [at(v, 0, i), length], 1, () => taSeries.sma(source, length))\n : taSeries.sma(source, length),\n ema: (source: Series, length: number): Series =>\n stepped('ema', () => taStep.ema(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.ema(source, length)),\n rma: (source: Series, length: number): Series =>\n stepped('rma', () => taStep.rma(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.rma(source, length)),\n wma: (source: Series, length: number | Series): Series =>\n typeof length === 'number'\n ? stepped('wma', taStep.wma, [source], (v, i) => [at(v, 0, i), length], 1, () => taSeries.wma(source, length))\n : taSeries.wma(source, length),\n rsi: (source: Series, length: number | Series): Series =>\n typeof length === 'number'\n ? stepped('rsi', () => taStep.rsi(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.rsi(source, length))\n : taSeries.rsi(source, length),\n change: (source: Series, length: number = 1): Series =>\n stepped('change', () => taStep.change(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.change(source, length)),\n mom: (source: Series, length: number): Series =>\n stepped('mom', () => taStep.mom(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.mom(source, length)),\n roc: (source: Series, length: number): Series =>\n stepped('roc', () => taStep.roc(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.roc(source, length)),\n cum: (source: Series): Series =>\n stepped('cum', taStep.cum, [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.cum(source)),\n stdev: (source: Series, length: number | Series, biased: boolean = true): Series =>\n typeof length === 'number'\n ? stepped('stdev', taStep.stdev, [source], (v, i) => [at(v, 0, i), length, biased], 1, () => taSeries.stdev(source, length, biased))\n : taSeries.stdev(source, length, biased),\n variance: (source: Series, length: number | Series, biased: boolean = true): Series =>\n typeof length === 'number'\n ? stepped('variance', taStep.variance, [source], (v, i) => [at(v, 0, i), length, biased], 1, () =>\n taSeries.variance(source, length, biased))\n : taSeries.variance(source, length, biased),\n crossover: (a: Series, b: Series | number): Series =>\n stepped('crossover', taStep.crossover, typeof b === 'number' ? [a] : [a, b],\n (v, i) => [at(v, 0, i), typeof b === 'number' ? b : at(v, 1, i)], 1, () => taSeries.crossover(a, b)),\n crossunder: (a: Series, b: Series | number): Series =>\n stepped('crossunder', taStep.crossunder, typeof b === 'number' ? [a] : [a, b],\n (v, i) => [at(v, 0, i), typeof b === 'number' ? b : at(v, 1, i)], 1, () => taSeries.crossunder(a, b)),\n cross: (a: Series, b: Series | number): Series =>\n stepped('cross', taStep.cross, typeof b === 'number' ? [a] : [a, b],\n (v, i) => [at(v, 0, i), typeof b === 'number' ? b : at(v, 1, i)], 1, () => taSeries.cross(a, b)),\n barssince: (condition: Series): Series =>\n stepped('barssince', taStep.barssince, [condition], (v, i) => [at(v, 0, i) === 1], 1, () => taSeries.barssince(condition)),\n valuewhen: (condition: Series, source: Series, occurrence: number): Series =>\n stepped('valuewhen', () => taStep.valuewhen(occurrence), [condition, source], (v, i) => [at(v, 0, i) === 1, at(v, 1, i)], 1,\n () => taSeries.valuewhen(condition, source, occurrence)),\n macd: (source: Series, fastLength: number, slowLength: number, signalLength: number): [Series, Series, Series] =>\n stepped('macd', () => taStep.macd(fastLength, slowLength, signalLength), [source], (v, i) => [at(v, 0, i)], 3, () =>\n taSeries.macd(source, fastLength, slowLength, signalLength)),\n bb: (source: Series, length: number, mult: number): [Series, Series, Series] =>\n stepped('bb', () => taStep.bb(length, mult), [source], (v, i) => [at(v, 0, i)], 3, () => taSeries.bb(source, length, mult)),\n hma: (source: Series, length: number): Series =>\n stepped('hma', () => taStep.hma(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.hma(source, length)),\n dev: (source: Series, length: number): Series =>\n stepped('dev', () => taStep.dev(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.dev(source, length)),\n cci: (source: Series, length: number): Series =>\n stepped('cci', () => taStep.cci(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.cci(source, length)),\n percentrank: (source: Series, length: number): Series =>\n stepped('percentrank', () => taStep.percentrank(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.percentrank(source, length)),\n median: (source: Series, length: number): Series =>\n stepped('median', () => taStep.median(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.median(source, length)),\n linreg: (source: Series, length: number, offset: number = 0): Series =>\n stepped('linreg', () => taStep.linreg(length, offset), [source], (v, i) => [at(v, 0, i)], 1, () =>\n taSeries.linreg(source, length, offset)),\n correlation: (a: Series, b: Series, length: number): Series =>\n stepped('correlation', () => taStep.correlation(length), [a, b], (v, i) => [at(v, 0, i), at(v, 1, i)], 1, () =>\n taSeries.correlation(a, b, length)),\n stoch: (source: Series, highSource: Series, lowSource: Series, length: number): Series =>\n stepped('stoch', () => taStep.stoch(length), [source, highSource, lowSource], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1,\n () => taSeries.stoch(source, highSource, lowSource, length)),\n};\n\n// The library's own `ta` object (bars-first functions) is not a script member.\nconst { ta: _libraryTa, ...taFunctions } = taSeries;\nvoid _libraryTa;\n\n/** ta.* with the chart-implicit (bars-first) functions bound to the context,\n * so scripts call them like `ta.tr(true)`, `ta.atr(14)`. Its members and their documentation: {@link TaNamespace}. */\nconst taMembers = strictNamespace('ta', outsideBarLoops({\n ...taFunctions,\n ...steppedTa,\n tr: (handleNa: boolean = false): Series =>\n stepped('tr', () => taStep.tr(handleNa), [high, low, close], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1, () =>\n taSeries.tr(bars(), handleNa)),\n atr: (length: number): Series =>\n stepped('atr', () => taStep.atr(length), [high, low, close], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1, () =>\n taSeries.atr(bars(), length)),\n sar: (start?: number, inc?: number, max?: number): Series => taSeries.sar(bars(), start, inc, max),\n wpr: (length: number = 14): Series =>\n stepped('wpr', () => taStep.wpr(length), [high, low, close], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1, () =>\n taSeries.wpr(bars(), length)),\n supertrend: (factor: number, atrLength: number): [Series, Series] =>\n stepped('supertrend', () => taStep.supertrend(factor, atrLength), [high, low, close],\n (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 2, () => taSeries.supertrend(bars(), factor, atrLength)),\n dmi: (diLength: number, adxSmoothing: number): [Series, Series, Series] =>\n stepped('dmi', () => taStep.dmi(diLength, adxSmoothing), [high, low, close],\n (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 3, () => taSeries.dmi(bars(), diLength, adxSmoothing)),\n kc: (source: Series, length: number, mult: number, useTrueRange?: boolean): [Series, Series, Series] =>\n taSeries.kc(bars(), source, length, mult, useTrueRange),\n kcw: (source: Series, length?: number, mult?: number, useTrueRange?: boolean): Series =>\n taSeries.kcw(bars(), source, length, mult, useTrueRange),\n ichimoku: (\n conversionPeriods: number,\n basePeriods: number,\n laggingSpan2Periods: number,\n displacement: number\n ): [Series, Series, Series, Series, Series] =>\n taSeries.ichimoku(bars(), conversionPeriods, basePeriods, laggingSpan2Periods, displacement),\n /** `ta.highest(source, length)` or `ta.highest(length)` (source = high). */\n highest: (sourceOrLength: Series | number, length?: number | Series): Series => {\n const source = typeof sourceOrLength === 'number' ? high : sourceOrLength;\n const len = typeof sourceOrLength === 'number' ? sourceOrLength : length!;\n return typeof len === 'number'\n ? stepped('highest', taStep.highest, [source], (v, i) => [at(v, 0, i), len], 1, () => taSeries.highest(source, len))\n : taSeries.highest(source, len);\n },\n /** `ta.lowest(source, length)` or `ta.lowest(length)` (source = low). */\n lowest: (sourceOrLength: Series | number, length?: number | Series): Series => {\n const source = typeof sourceOrLength === 'number' ? low : sourceOrLength;\n const len = typeof sourceOrLength === 'number' ? sourceOrLength : length!;\n return typeof len === 'number'\n ? stepped('lowest', taStep.lowest, [source], (v, i) => [at(v, 0, i), len], 1, () => taSeries.lowest(source, len))\n : taSeries.lowest(source, len);\n },\n /** `ta.highestbars(source, length)` or `ta.highestbars(length)` (source = high); offsets are 0 or negative. */\n highestbars: (sourceOrLength: Series | number, length?: number | Series): Series =>\n typeof sourceOrLength === 'number'\n ? taSeries.highestbars(high, sourceOrLength)\n : taSeries.highestbars(sourceOrLength, length!),\n /** `ta.lowestbars(source, length)` or `ta.lowestbars(length)` (source = low); offsets are 0 or negative. */\n lowestbars: (sourceOrLength: Series | number, length?: number | Series): Series =>\n typeof sourceOrLength === 'number'\n ? taSeries.lowestbars(low, sourceOrLength)\n : taSeries.lowestbars(sourceOrLength, length!),\n /** `ta.vwap(source, anchor?, stdev_mult?)` with the chart volume; the default anchor is a new trading day\n * and the first bar: as in PineScript, the first loaded bars (a day in progress) have a value. On D / W / M\n * charts every bar is a new day (no time zone or session needed); on intraday charts it needs the chart context\n * (timeframe, time zone, session). */\n vwap: ((source: Series, anchor?: Series, stdev_mult?: number): Series | [Series, Series, Series] => {\n const a = anchor ?? vwapAnchor();\n return stdev_mult === undefined ? taSeries.vwap(source, volume, a) : taSeries.vwapBands(source, volume, a, stdev_mult);\n }) as {\n (source: Series, anchor?: Series): Series;\n (source: Series, anchor: Series | undefined, stdev_mult: number): [Series, Series, Series];\n },\n /** `ta.vwma(source, length)` with the chart volume, as PineScript; a third argument gives another volume. */\n vwma: (source: Series, length: number, vol?: Series): Series =>\n stepped('vwma', () => taStep.vwma(length), [source, vol ?? volume], (v, i) => [at(v, 0, i), at(v, 1, i)], 1, () =>\n taSeries.vwma(source, length, vol ?? volume)),\n /** `ta.mfi(source, length)` with the chart volume (PineScript takes 2 arguments). */\n mfi: (source: Series, length: number): Series =>\n stepped('mfi', () => taStep.mfi(length), [source, volume], (v, i) => [at(v, 0, i), at(v, 1, i)], 1, () =>\n taSeries.mfi(source, length, volume)),\n /** `ta.pivothigh(source, leftbars, rightbars)` or `ta.pivothigh(leftbars, rightbars)` (source = high).\n * The value appears `rightbars` bars after the pivot bar, as in PineScript. */\n pivothigh: (sourceOrLeft: Series | number, leftOrRight: number | Series, rightbars?: number | Series): Series =>\n typeof sourceOrLeft === 'number'\n ? taSeries.pivothigh(high, sourceOrLeft, leftOrRight)\n : taSeries.pivothigh(sourceOrLeft, leftOrRight, rightbars!),\n /** `ta.pivotlow(source, leftbars, rightbars)` or `ta.pivotlow(leftbars, rightbars)` (source = low). */\n pivotlow: (sourceOrLeft: Series | number, leftOrRight: number | Series, rightbars?: number | Series): Series =>\n typeof sourceOrLeft === 'number'\n ? taSeries.pivotlow(low, sourceOrLeft, leftOrRight)\n : taSeries.pivotlow(sourceOrLeft, leftOrRight, rightbars!),\n // PineScript variables of the chart bars: `ta.obv`, not `ta.obv()`.\n obv: barsSeries(taSeries.obv),\n pvt: barsSeries(taSeries.pvt),\n accdist: barsSeries(taSeries.accdist),\n nvi: barsSeries(taSeries.nvi),\n pvi: barsSeries(taSeries.pvi),\n iii: barsSeries(taSeries.iii),\n wad: barsSeries(taSeries.wad),\n wvad: barsSeries(taSeries.wvad),\n zigzag: (deviation?: number, depth?: number, backstep?: number): [Series, Series, Series] =>\n taSeries.zigzag(bars(), deviation, depth, backstep),\n}));\n/**\n * Technical analysis: moving averages, oscillators, bands, crosses, pivots and volume indicators. Each function\n * computes a whole Series in one call: call it before any `eachBar()` loop and read a bar's value with `c.get(x)`.\n * @example\n * ```js\n * const fast = ta.ema(close, 12), slow = ta.ema(close, 26);\n * plot(fast, \"Fast\"); plot(slow, \"Slow\");\n * ```\n */\nexport const ta: TaNamespace = taMembers;\nsameKeys<typeof taMembers, TaNamespace>(true);\n\n/**\n * Fills the gaps of a Series: each na value (NaN) becomes the last value that was not na. Values before the first\n * non-na value stay na; +/-Infinity is kept.\n * @param source - The Series to fill.\n * @returns A Series without gaps after its first value.\n * @example\n * ```js\n * const pivot = fixnan(ta.pivothigh(5, 5));\n * plot(pivot, \"Last pivot high\", { style: plot.style_stepline });\n * ```\n */\nexport function fixnan(source: Series): Series;\n/**\n * Fills the gaps of a per-bar colour array: each na entry (`undefined`) becomes the last colour that was not na.\n * @param source - One colour per bar, as made by `color.when()`.\n * @returns A colour array without gaps after its first colour.\n * @example\n * ```js\n * const trendColor = fixnan(color.when(ta.crossover(close, ta.sma(close, 20)), color.green));\n * barcolor(trendColor);\n * ```\n */\nexport function fixnan(source: Array<string | undefined>): Array<string | undefined>;\nexport function fixnan(source: Series | Array<string | undefined>): Series | Array<string | undefined> {\n if (source instanceof Series) return Series.fromArray(ctxBars, fixnanValues(source.toArray()));\n // the colours are the same set: the palette stays\n return withPalette(fixnanValues(source), colorPalettes.get(source));\n}\n\n/**\n * Tells, bar by bar, whether a Series is na (NaN or +/-Infinity): a Series of 1 where it is, 0 elsewhere.\n * @param x - The Series to test.\n * @returns A Series of 1 / 0.\n * @example\n * ```js\n * const ma = ta.sma(close, 50);\n * bgcolor(color.when(na(ma), color.new(color.gray, 90)), { title: \"Warming up\" });\n * ```\n */\nexport function na(x: Series): Series;\n/**\n * Tells whether one value is na: NaN, +/-Infinity, `undefined` or `null` (a colour or a drawing), a deleted drawing,\n * or an empty text. Use it on the numbers of a bar loop.\n * @param x - The value to test.\n * @returns true when the value is na.\n * @example\n * ```js\n * const ma = ta.sma(close, 50);\n * eachBar((c) => { if (!na(c.get(ma)) && c.close > c.get(ma)) label.new(c.i, c.high, \"Above\"); });\n * ```\n */\nexport function na(x: unknown): boolean;\nexport function na(x: unknown): Series | boolean {\n if (x instanceof Series) return Series.fromArray(ctxBars, x.toArray().map((v) => (isNA(v) ? 1 : 0)));\n return x === '' || isNA(x);\n}\n\n/**\n * Replaces the na values of a Series (NaN or +/-Infinity) with a replacement, bar by bar, e.g. to start a sum at 0.\n * @param source - The Series to clean.\n * @param replacement - The value for the na bars: a number, or a Series (its value on the same bar). Default: 0.\n * @returns A Series without na values (unless the replacement is na).\n * @example\n * ```js\n * const change = nz(close.sub(close.offset(1)));\n * plot(change, \"Change\", { style: plot.style_columns });\n * ```\n */\nexport function nz(source: Series, replacement?: number | Series): Series;\n/**\n * Returns a value, or a replacement when it is na (NaN, +/-Infinity, `undefined`, `null`). Use it on the numbers of\n * a bar loop.\n * @param source - The value to check.\n * @param replacement - The value returned when `source` is na. Default: 0.\n * @returns `source`, or `replacement` when `source` is na.\n * @example\n * ```js\n * const total = eachBar((c) => nz(c.prev()) + c.volume);\n * plot(total, \"Cumulative volume\");\n * ```\n */\nexport function nz<T>(source: T, replacement?: T): T;\nexport function nz(source: unknown, replacement: unknown = 0): unknown {\n if (source instanceof Series) {\n const values = source.toArray();\n const rep = replacement instanceof Series ? replacement.toArray() : undefined;\n const r = rep ? 0 : Number(replacement);\n return Series.fromArray(ctxBars, values.map((v, i) => (isNA(v) ? (rep ? rep[i]! : r) : v)));\n }\n return nzValue(source, replacement);\n}\n\n// \u2500\u2500 Color helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * The palette of a per-bar colour array: the constant colours it chooses from (PineScript compiles the colours of a\n * conditional colour expression into a palette, in their order in the expression). An array without one (colours\n * computed per bar) has none: its colours cannot be changed one by one.\n */\nconst colorPalettes = new WeakMap<object, string[]>();\n\nfunction withPalette<T extends object>(colors: T, palette: string[] | undefined): T {\n if (palette?.length) colorPalettes.set(colors, palette);\n return colors;\n}\n\n/** The palette of a colour argument given as a per-bar array, if it has one. */\nfunction paletteOfColors(col: unknown): string[] | undefined {\n return typeof col === 'object' && col !== null ? colorPalettes.get(col) : undefined;\n}\n\n/** Per-bar color selection: truthy \u2192 colorTrue, else colorFalse.\n * colorFalse may be omitted (PineScript `na`): those bars get no color,\n * which bgcolor()/barcolor() skip. */\nfunction colorWhen(cond: Series, colorTrue: string, colorFalse: string): string[];\nfunction colorWhen(cond: Series, colorTrue: string, colorFalse?: string): Array<string | undefined>;\nfunction colorWhen(cond: Series, colorTrue: string, colorFalse?: string): Array<string | undefined> {\n const colors = cond.toArray().map((v) => (!isNA(v) && v !== 0 ? colorTrue : colorFalse));\n const palette = [colorTrue, ...(colorFalse !== undefined && colorFalse !== colorTrue ? [colorFalse] : [])];\n return withPalette(colors, palette);\n}\n\ntype GradientColor = string | null | undefined;\n\n/** PineScript `color.from_gradient(value, bottom_value, top_value, bottom_color, top_color)`. With numbers and\n * colours: one colour. When an argument is a Series (or a colour is a per-bar array, as from `color.when`): the\n * colour of each bar, the rule of the number form applied to the values of that bar (#187), for\n * plot()/fill()/bgcolor()/barcolor(). */\nfunction fromGradient(\n value: number,\n bottom_value: number,\n top_value: number,\n bottom_color: GradientColor,\n top_color: GradientColor\n): string;\nfunction fromGradient(\n value: number | Series,\n bottom_value: number | Series,\n top_value: number | Series,\n bottom_color: GradientColor | readonly GradientColor[],\n top_color: GradientColor | readonly GradientColor[]\n): string | string[];\nfunction fromGradient(\n value: number | Series,\n bottom_value: number | Series,\n top_value: number | Series,\n bottom_color: GradientColor | readonly GradientColor[],\n top_color: GradientColor | readonly GradientColor[]\n): string | string[] {\n const args = [value, bottom_value, top_value];\n if (!args.some((a) => a instanceof Series) && !Array.isArray(bottom_color) && !Array.isArray(top_color)) {\n return colorCore.from_gradient(value as number, bottom_value as number, top_value as number, bottom_color as string, top_color as string);\n }\n const [v, lo, hi] = args.map((a) => (a instanceof Series ? a.toArray() : undefined));\n const at = (arr: number[] | undefined, num: number | Series, i: number) => (arr ? arr[i]! : (num as number));\n const colorAt = (c: GradientColor | readonly GradientColor[], i: number) => (Array.isArray(c) ? c[i] : (c as GradientColor));\n return Array.from({ length: ctxBars.length }, (_, i) =>\n colorCore.from_gradient(at(v, value, i), at(lo, bottom_value, i), at(hi, top_value, i), colorAt(bottom_color, i) as string, colorAt(top_color, i) as string)\n );\n}\n\nconst colorMembers = strictNamespace('color', {\n ...colorCore,\n new: colorCore.new_color,\n from_gradient: fromGradient,\n when: colorWhen,\n /**\n * Not in PineScript: the colour faded by `amount`, from 0 (unchanged) to 1 (invisible): `color.fade(color.red, 0.8)`\n * is `color.new(color.red, 80)`.\n */\n fade: (c: string, amount: number): string => {\n if (typeof amount !== 'number' || !(amount >= 0 && amount <= 1)) {\n throw new ScriptError(`color.fade(): the amount is from 0 (unchanged) to 1 (invisible), got ${shown(amount)}.`);\n }\n return colorCore.new_color(c, amount * 100);\n },\n});\n/**\n * Colours: named colours (`color.red`, `color.teal`...), `color.new` for transparency, `color.rgb`, gradients, and\n * `color.when` to pick a colour per bar for `plot()`, `fill()`, `bgcolor()` and `barcolor()`.\n * @example\n * ```js\n * const up = close.gt(open);\n * plot(close, \"Close\", { color: color.when(up, color.green, color.red) });\n * bgcolor(color.new(color.blue, 90));\n * ```\n */\nexport const color: ColorNamespace = colorMembers;\nsameKeys<typeof colorMembers, ColorNamespace>(true);\n\n// \u2500\u2500 Drawing declarations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Options of {@link plot}. */\nexport interface ScriptPlotOptions {\n /** Shift in bars: the value of bar i is drawn on bar i + offset (negative: to the left). Default: 0. */\n offset?: number;\n /** One colour, or one colour per bar (`color.when()`, `undefined` = not drawn). Default: blue `#2962FF`. */\n color?: string | string[];\n /** Line width in pixels. Default: 1. */\n linewidth?: number;\n /** How the values are drawn: `plot.style_line`, `plot.style_histogram`, `plot.style_columns`... Default: `plot.style_line`. */\n style?: PlotConfig['style'];\n /** Dash pattern of the line: `plot.linestyle_solid`, `plot.linestyle_dashed` or `plot.linestyle_dotted` (one for all bars). Default: solid. */\n linestyle?: PlotConfig['linestyle'];\n /** Where the plot shows: `display.all`, `display.none` (hidden, still listed), `display.pane`, `display.status_line`, `display.data_window`. Default: `display.all`. */\n display?: PlotConfig['display'];\n /** Base level the histogram bars start from (`plot.style_histogram`). Default: 0. */\n histbase?: number;\n /** true: draw on the price pane even when the script has its own pane. Default: false. */\n force_overlay?: boolean;\n /** false: not listed in the style settings of the script. Default: true. */\n editable?: boolean;\n}\n\n/**\n * The titles an output gets when the script gives none (`plot` is \"Plot\", `hline` is \"Level\"...): the style settings\n * and the alert lists show them.\n */\nexport const DEFAULT_OUTPUT_TITLES = {\n /** Title of a `plot()` without one. */\n plot: 'Plot',\n /** Title of an `hline()` without one. */\n hline: 'Level',\n /** Title of a `fill()` between two plots without one. */\n plotFill: 'Plots Background',\n /** Title of a `fill()` between two hlines without one. */\n hlineFill: 'Hlines Background',\n /** Title of a `plotshape()` without one. */\n shape: 'Shapes',\n /** Title of a `plotchar()` without one. */\n char: 'Chars',\n /** Title of a `plotarrow()` without one. */\n arrow: 'Arrows',\n /** Title of a `bgcolor()` without one. */\n bgcolor: 'Background Color',\n /** Title of a `barcolor()` without one. */\n barcolor: 'Bar Color',\n /** Title of a `plotcandle()` without one. */\n candle: 'PlotCandle',\n /** Title of a `plotbar()` without one. */\n bar: 'PlotBar',\n} as const;\n\nconst PLOT_OPTION_KEYS = ['offset', 'color', 'linewidth', 'style', 'linestyle', 'display', 'histbase', 'force_overlay', 'editable'] as const;\n\n/**\n * Draws a Series on the chart (a line by default, or a histogram, columns, area, circles...) and lists it in the\n * legend and the settings. Bars whose value is na (NaN or +/-Infinity) are not drawn.\n * @param source - The values to draw: a Series, or a number for the same value on every bar.\n * @param title - Name of the plot in the legend, the settings and the alerts. Default: \"Plot\".\n * @param options - Colour, width, style, line style, offset, display... Default: `{}` (a blue line).\n * @returns A handle to pass to `fill()`.\n * @example\n * ```js\n * const fast = plot(ta.ema(close, 12), \"Fast\", { color: color.teal, linewidth: 2 });\n * const slow = plot(ta.ema(close, 26), \"Slow\", { color: color.orange });\n * fill(fast, slow, color.new(color.gray, 85));\n * ```\n */\nfunction plotImpl(source: Series | number, title: string = DEFAULT_OUTPUT_TITLES.plot, options: ScriptPlotOptions = {}): PlotHandle {\n if (intrabarRun) return { id: '', kind: 'plot' }; // dropped: an intrabar run's outputs aren't read\n const c = collector();\n if (c.strict && typeof title !== 'string') throw new ScriptError(`plot(): the title is a text, e.g. plot(rsi, \"RSI\"), got ${shown(title)}.`);\n checkOptions('plot', options, PLOT_OPTION_KEYS);\n const series = typeof source === 'number' ? new Series(ctxBars, () => source) : source;\n if (!(series instanceof Series)) {\n throw new TypeError(`plot(): the value to plot is a series (close, ta.sma(close, 14)...) or a number, got ${shown(source)}.`);\n }\n const id = scriptOptions.plotIds === 'title' ? slugId(title, `plot${c.plotConfig.length}`, (c.plotIdsTaken ??= new Set())) : `plot${c.plotConfig.length}`;\n const perBar = Array.isArray(options.color) ? options.color : undefined;\n const palette = scriptOptions.palette === true ? DEFAULT_PALETTE : Array.isArray(scriptOptions.palette) && scriptOptions.palette.length ? scriptOptions.palette : null;\n let fallback = '#2962FF';\n if (palette && options.color === undefined) {\n const k = c.paletteUsed ?? 0;\n c.paletteUsed = k + 1;\n fallback = palette[k % palette.length]!;\n }\n const staticColor = typeof options.color === 'string' ? options.color : (perBar?.[perBar.length - 1] ?? fallback);\n c.plotConfig.push({\n id,\n title,\n color: staticColor,\n lineWidth: options.linewidth,\n style: options.style,\n linestyle: options.linestyle,\n display: options.display,\n histbase: options.histbase,\n forceOverlay: options.force_overlay,\n ...(options.editable === false ? { editable: false } : {}),\n ...(paletteOfColors(perBar) ? { palette: paletteOfColors(perBar) } : {}),\n });\n c.outputs.push({ kind: 'plot', id, title });\n const values = series.toArray();\n const b = bars();\n let data: TimeValue[] = [];\n // offset (PineScript plot(offset = k)): the value and colour of bar i are drawn on bar i + k; bars past the\n // chart's first or last bar are dropped\n const off = Math.trunc(options.offset ?? 0);\n let j0 = Math.max(0, off);\n // An incremental run (#196) keeps the points of the bars whose values did not change; pos[j]: points before bar j\n const run = incremental.active;\n const slot = run ? run.plotSlot++ : -1;\n let pos: number[] = [];\n const prev = run?.mode === 'resume' ? run.prev?.plots[slot] : undefined;\n const sig = `${off}|${perBar ? 'colors' : ''}`;\n if (prev && prev.sig === sig) {\n const from = Math.max(j0, run!.from + Math.min(0, off));\n if (from < prev.pos.length) {\n // the points are given to the host: a copy of the kept ones (the positions are the run's own)\n data = prev.data.slice(0, prev.pos[from]);\n pos = prev.pos;\n pos.length = from;\n j0 = from;\n }\n }\n for (let j = 0; j < j0; j++) pos[j] ??= 0;\n let j = j0;\n for (; j < b.length && j - off < b.length; j++) {\n pos[j] = data.length;\n const i = j - off;\n const value = values[i];\n if (value === undefined || !Number.isFinite(value)) continue; // PineScript plots +/-Infinity as na\n data.push(perBar ? { time: b[j]!.time, value, color: perBar[i] } : { time: b[j]!.time, value });\n }\n for (; j <= b.length; j++) pos[j] = data.length;\n if (run) run.next.plots[slot] = { data, pos, sig };\n c.plots[id] = data;\n return { id, kind: 'plot' };\n}\n\n/** The `plot()` function with its `plot.style_*` and `plot.linestyle_*` constants. */\nexport interface PlotFunction {\n /**\n * Draws a Series on the chart (a line by default, or a histogram, columns, area, circles...) and lists it in the\n * legend and the settings. Bars whose value is na (NaN or +/-Infinity) are not drawn.\n * @param source - The values to draw: a Series, or a number for the same value on every bar.\n * @param title - Name of the plot in the legend, the settings and the alerts. Default: \"Plot\".\n * @param options - Colour, width, style, line style, offset, display... Default: `{}` (a blue line).\n * @returns A handle to pass to `fill()`.\n */\n (source: Series | number, title?: string, options?: ScriptPlotOptions): PlotHandle;\n /** Style: a line through every value; na values are bridged. */\n readonly style_line: 'line';\n /** Style: a line with a gap where the value is na. */\n readonly style_linebr: 'linebr';\n /** Style: steps (horizontal then vertical moves); na values are bridged. */\n readonly style_stepline: 'stepline';\n /** Style: steps with a gap where the value is na. */\n readonly style_steplinebr: 'steplinebr';\n /** Style: steps with a diamond on each change. */\n readonly style_stepline_diamond: 'stepline_diamond';\n /** Style: a thin bar from the base line (`histbase`, default 0) to each value. */\n readonly style_histogram: 'histogram';\n /** Style: a wide column from the base line to each value. */\n readonly style_columns: 'columns';\n /** Style: a line with the area down to the base line filled. */\n readonly style_area: 'area';\n /** Style: a filled area with a gap where the value is na. */\n readonly style_areabr: 'areabr';\n /** Style: a dot on each value. */\n readonly style_circles: 'circles';\n /** Style: a cross on each value. */\n readonly style_cross: 'cross';\n /** Line style: solid. */\n readonly linestyle_solid: 'solid';\n /** Line style: dotted. */\n readonly linestyle_dotted: 'dotted';\n /** Line style: dashed. */\n readonly linestyle_dashed: 'dashed';\n}\n\n/**\n * Draws a Series on the chart and lists it in the legend and the settings; `plot.style_*` and `plot.linestyle_*`\n * pick how it is drawn.\n * @example\n * ```js\n * const fast = plot(ta.ema(close, 12), \"Fast\", { color: color.teal, linewidth: 2 });\n * plot(ta.rsi(close, 14), \"RSI\", { style: plot.style_histogram });\n * ```\n */\nexport const plot: PlotFunction = Object.assign(plotImpl, {\n style_line: 'line',\n style_linebr: 'linebr',\n style_stepline: 'stepline',\n style_steplinebr: 'steplinebr',\n style_stepline_diamond: 'stepline_diamond',\n style_histogram: 'histogram',\n style_columns: 'columns',\n style_area: 'area',\n style_areabr: 'areabr',\n style_circles: 'circles',\n style_cross: 'cross',\n linestyle_solid: 'solid',\n linestyle_dotted: 'dotted',\n linestyle_dashed: 'dashed',\n} as const);\n\nexport interface ScriptHLineOptions {\n /** Colour of the line. Default: the host's (grey). */\n color?: string;\n /** Line style: `hline.style_solid`, `hline.style_dotted` or `hline.style_dashed`. Default: dashed. */\n linestyle?: HLineConfig['linestyle'];\n /** Width of the line in pixels. Default: 1. */\n linewidth?: number;\n /** false: not listed in the style settings of the script. Default: true. */\n editable?: boolean;\n}\n\n/**\n * Draws a horizontal line at a fixed price (a level such as 70 / 30 on an oscillator).\n * @param price - Price of the line.\n * @param title - Name of the line in the settings. Default: \"Level\".\n * @param options - Colour, line style and width. Default: `{}` (a dashed line).\n * @returns A handle to pass to `fill()`.\n */\nfunction hlineImpl(price: number, title: string = DEFAULT_OUTPUT_TITLES.hline, options: ScriptHLineOptions = {}): PlotHandle {\n const c = collector();\n checkOptions('hline', options, ['color', 'linestyle', 'linewidth', 'editable']);\n const id = `hline${c.hlineConfig.length}`;\n c.hlineConfig.push({\n id,\n price,\n title,\n color: options.color,\n linestyle: options.linestyle ?? 'dashed',\n linewidth: options.linewidth,\n ...(options.editable === false ? { editable: false } : {}),\n });\n return { id, kind: 'hline' };\n}\n\n/** The `hline()` function with its `hline.style_*` constants. */\nexport interface HlineFunction {\n /**\n * Draws a horizontal line at a fixed price (a level such as 70 / 30 on an oscillator).\n * @param price - Price of the line.\n * @param title - Name of the line in the settings. Default: \"Level\".\n * @param options - Colour, line style and width. Default: `{}` (a dashed line).\n * @returns A handle to pass to `fill()`.\n */\n (price: number, title?: string, options?: ScriptHLineOptions): PlotHandle;\n /** Line style: solid. */\n readonly style_solid: 'solid';\n /** Line style: dotted. */\n readonly style_dotted: 'dotted';\n /** Line style: dashed (the default). */\n readonly style_dashed: 'dashed';\n}\n\n/**\n * Draws a horizontal line at a fixed price; `hline.style_*` picks its line style.\n * @example\n * ```js\n * const top = hline(70, \"Overbought\", { color: color.red });\n * const bottom = hline(30, \"Oversold\", { linestyle: hline.style_dotted });\n * fill(top, bottom, color.new(color.purple, 90));\n * ```\n */\nexport const hline: HlineFunction = Object.assign(hlineImpl, {\n style_solid: 'solid',\n style_dotted: 'dotted',\n style_dashed: 'dashed',\n} as const);\n\nexport interface ScriptFillOptions {\n /** Fill colour: one colour, or one per bar from `color.when()`. */\n color?: string | string[];\n /** Name of the fill in the settings. Default: \"Plots Background\" / \"Hlines Background\". */\n title?: string;\n /** false: not listed in the style settings of the script. Default: true. */\n editable?: boolean;\n}\n\n/** A fill colour argument: a colour, na (null / undefined), or a per-bar array from color.when(). */\nexport type ScriptFillColor = string | null | undefined | Array<string | null | undefined>;\n\n/** A gradient value argument: a number or a Series. */\nexport type ScriptFillValue = number | Series;\n\nfunction perBarValues(v: ScriptFillValue, n: number): number[] {\n return v instanceof Series ? v.toArray().slice(0, n) : new Array<number>(n).fill(v);\n}\n\nfunction perBarColors(c: ScriptFillColor, n: number): Array<string | null> {\n if (Array.isArray(c)) return Array.from({ length: n }, (_, i) => c[i] ?? null);\n return new Array<string | null>(n).fill(c ?? null);\n}\n\n/** The colour of every bar when it is the same on all of them (and not na). */\nfunction sameColor(colors: Array<string | null>): string | undefined {\n const first = colors[0];\n return first && colors.every((x) => x === first) ? first : undefined;\n}\n\n/**\n * Colours the space between two plots or two hlines, with an options object.\n * @param a - First plot or hline (the handle `plot()` / `hline()` returned).\n * @param b - Second plot or hline, of the same kind as `a`.\n * @param options - Colour (one, or one per bar from `color.when()`), title, editable. Default: `{}`.\n * @example\n * ```js\n * const upper = plot(ta.sma(high, 20), \"Upper\");\n * const lower = plot(ta.sma(low, 20), \"Lower\");\n * fill(upper, lower, { color: color.new(color.blue, 85), title: \"Channel\" });\n * ```\n */\nexport function fill(a: PlotHandle, b: PlotHandle, options?: ScriptFillOptions): void;\n/**\n * Colours the space between two plots or two hlines with one colour (or one per bar).\n * @param a - First plot or hline (the handle `plot()` / `hline()` returned).\n * @param b - Second plot or hline, of the same kind as `a`.\n * @param color - Fill colour, or one per bar from `color.when()`; na (null) leaves a bar unfilled.\n * @param title - Name of the fill in the settings. Default: \"Plots Background\" / \"Hlines Background\".\n * @param rest - `editable` (false keeps it out of the settings); `show_last`, `fillgaps` and `display` are accepted\n * and not used.\n * @example\n * ```js\n * const top = hline(70), bottom = hline(30);\n * fill(top, bottom, color.new(color.purple, 90), \"Zone\");\n * ```\n */\nexport function fill(a: PlotHandle, b: PlotHandle, color: ScriptFillColor, title?: string, ...rest: unknown[]): void;\n/**\n * Colours the space between two plots with a gradient: `top_color` at `top_value`, `bottom_color` at\n * `bottom_value`; the values and colours may change from bar to bar.\n * @param a - First plot (the handle `plot()` returned).\n * @param b - Second plot.\n * @param top_value - Price of the top colour: a number or a Series.\n * @param bottom_value - Price of the bottom colour: a number or a Series.\n * @param top_color - Colour at the top, or one per bar.\n * @param bottom_color - Colour at the bottom, or one per bar.\n * @param title - Name of the fill in the settings. Default: \"Plots Background\".\n * @param rest - `editable` (false keeps it out of the settings); other arguments are accepted and not used.\n * @example\n * ```js\n * const basis = ta.sma(close, 20);\n * const p = plot(close), q = plot(basis);\n * fill(p, q, high, basis, color.green, color.new(color.green, 100));\n * ```\n */\nexport function fill(\n a: PlotHandle,\n b: PlotHandle,\n top_value: ScriptFillValue,\n bottom_value: ScriptFillValue,\n top_color: ScriptFillColor,\n bottom_color: ScriptFillColor,\n title?: string,\n ...rest: unknown[]\n): void;\nexport function fill(a: PlotHandle, b: PlotHandle, ...args: unknown[]): void {\n if (intrabarRun) return; // dropped: an intrabar run's outputs aren't read\n const c = collector();\n const third = args[0];\n let perBar: string[] | undefined;\n let staticColor: string | undefined;\n let title: string | undefined;\n let gradient: FillGradient | undefined;\n let editable: unknown;\n /** The per-bar colour argument as given (its palette) */\n let perBarArg: unknown;\n if (typeof third === 'number' || third instanceof Series) {\n const n = ctxBars.bars.length;\n gradient = {\n topValue: perBarValues(third, n),\n bottomValue: perBarValues(args[1] as ScriptFillValue, n),\n topColor: perBarColors(args[2] as ScriptFillColor, n),\n bottomColor: perBarColors(args[3] as ScriptFillColor, n),\n };\n title = args[4] as string | undefined;\n editable = args[5];\n } else if (third !== null && typeof third === 'object' && !Array.isArray(third)) {\n const options = third as ScriptFillOptions;\n perBar = Array.isArray(options.color) ? options.color : undefined;\n perBarArg = perBar;\n staticColor = typeof options.color === 'string' ? options.color : undefined;\n title = options.title;\n editable = options.editable;\n } else {\n const color = third as ScriptFillColor;\n perBar = Array.isArray(color) ? color.map((x) => x ?? '') : undefined;\n perBarArg = Array.isArray(color) ? color : undefined;\n staticColor = typeof color === 'string' ? color : undefined;\n title = args[1] as string | undefined;\n editable = args[2];\n }\n const id = `fill${c.fillConfig.length}`;\n title ??= a.kind === 'hline' && b.kind === 'hline' ? DEFAULT_OUTPUT_TITLES.hlineFill : DEFAULT_OUTPUT_TITLES.plotFill;\n const topColor = gradient && sameColor(gradient.topColor);\n const bottomColor = gradient && sameColor(gradient.bottomColor);\n const hlines = a.kind === 'hline' && b.kind === 'hline';\n c.fillConfig.push({\n id,\n plot1: a.id,\n plot2: b.id,\n color: staticColor,\n // the per-bar data of a fill between plots is in the result\n ...(hlines ? { colors: perBar, gradient } : {}),\n title,\n ...(topColor ? { topColor } : {}),\n ...(bottomColor ? { bottomColor } : {}),\n ...(editable === false ? { editable: false } : {}),\n ...(paletteOfColors(perBarArg) ? { palette: paletteOfColors(perBarArg) } : {}),\n });\n if (hlines) return;\n c.fills.push({\n id,\n plot1: a.id,\n plot2: b.id,\n options: { color: staticColor, title },\n colors: perBar,\n gradient,\n });\n}\n\nexport interface PlotShapeOptions {\n style?: ShapeStyle;\n location?: MarkerLocation;\n color?: string;\n text?: string;\n textcolor?: string;\n size?: MarkerSize;\n /** Display offset in bars (marker shown at bar i + offset). */\n offset?: number;\n /** Hover tooltip (extension over PineScript, for label.new-style ports). */\n tooltip?: string;\n /** Draw on the main chart pane even when the script is not an overlay (PineScript `force_overlay`); default false. */\n force_overlay?: boolean;\n /** False: not listed in the Style settings of the study (PineScript `editable`); default true. */\n editable?: boolean;\n}\n\nexport interface PlotCharOptions extends Omit<PlotShapeOptions, 'style'> {\n char?: string;\n}\n\n/** PineScript shape.* style -> marker shape. */\nconst MARKER_SHAPES: Record<ShapeStyle, MarkerShape> = {\n xcross: 'xcross',\n cross: 'cross',\n triangleup: 'triangleUp',\n triangledown: 'triangleDown',\n flag: 'flag',\n circle: 'circle',\n arrowup: 'arrowUp',\n arrowdown: 'arrowDown',\n labelup: 'labelUp',\n labeldown: 'labelDown',\n square: 'square',\n diamond: 'diamond',\n};\n\n/**\n * Marker position of a PineScript location. With location.absolute the shape sits on the price: a label pointing\n * down above it, a label pointing up below it, the other shapes (and the characters) centred on it.\n */\nfunction markerPosition(location: MarkerLocation, shape: ShapeStyle | undefined): MarkerPosition {\n switch (location) {\n case 'abovebar':\n return 'aboveBar';\n case 'belowbar':\n return 'belowBar';\n case 'top':\n return 'top';\n case 'bottom':\n return 'bottom';\n case 'absolute':\n return shape === 'labeldown' ? 'atPriceTop' : shape === 'labelup' ? 'atPriceBottom' : 'atPriceMiddle';\n }\n}\n\n/** Default colour of plotshape / plotchar markers. */\nconst MARKER_COLOR = '#2962FF';\n\n/** The value of an output's series on each bar where it is not na (a condition: 1 or 0), at the bar it was computed\n * on: what PineScript gives for the output in an alert message. */\nfunction outputSeries(values: ArrayLike<unknown>, b: readonly Bar[]): TimeValue[] {\n const series: TimeValue[] = [];\n for (let i = 0; i < b.length; i++) {\n const v = values[i];\n if (typeof v === 'number' && Number.isFinite(v)) series.push({ time: b[i]!.time, value: v });\n else if (typeof v === 'boolean') series.push({ time: b[i]!.time, value: v ? 1 : 0 });\n }\n return series;\n}\n\n/** Shared emitter for plotshape()/plotchar(). Emits one marker per bar where\n * the condition is truthy (not na, not 0). A plotchar marker has the shape 'circle' and its character in `char`. */\nfunction emitMarkers(\n kind: 'shape' | 'char',\n condition: Series,\n title: string | undefined,\n options: PlotShapeOptions & PlotCharOptions\n): void {\n if (intrabarRun) return; // dropped: an intrabar run's outputs aren't read\n const c = collector();\n const id = `${kind}${c.shapeConfig.filter((s) => s.kind === kind).length}`;\n title ??= DEFAULT_OUTPUT_TITLES[kind];\n const style: ShapeStyle | 'char' = kind === 'shape' ? (options.style ?? 'xcross') : 'char';\n const char = kind === 'char' ? (options.char ?? '*') : undefined;\n const location = options.location ?? 'abovebar';\n c.shapeConfig.push({\n id,\n kind,\n title,\n style: kind === 'shape' ? (style as ShapeStyle) : undefined,\n char,\n location,\n color: options.color,\n text: options.text,\n textcolor: options.textcolor,\n size: options.size,\n offset: options.offset,\n forceOverlay: options.force_overlay,\n ...(options.editable === false ? { editable: false } : {}),\n });\n c.outputs.push({ kind, id, title });\n const shapeStyle = kind === 'shape' ? (style as ShapeStyle) : undefined;\n const template: Omit<MarkerData, 'time'> = {\n position: markerPosition(location, shapeStyle),\n shape: shapeStyle ? MARKER_SHAPES[shapeStyle] : 'circle',\n color: options.color ?? MARKER_COLOR,\n id,\n };\n if (char !== undefined) template.char = char;\n if (options.text !== undefined) template.text = options.text;\n if (options.textcolor !== undefined) template.textColor = options.textcolor;\n if (options.size !== undefined) template.size = options.size;\n if (options.tooltip !== undefined) template.tooltip = options.tooltip;\n if (options.force_overlay) template.forceOverlay = true;\n const values = condition.toArray();\n const b = bars();\n const off = options.offset ?? 0;\n c.outputValues[id] = outputSeries(values, b);\n for (let i = 0; i < b.length; i++) {\n const v = values[i];\n if (v === undefined || Number.isNaN(v) || v === 0) continue;\n const j = i + off;\n if (j < 0 || j >= b.length) continue;\n const time = b[j]!.time;\n c.markers.push(location === 'absolute' ? { time, ...template, price: v } : { time, ...template });\n }\n}\n\nconst SHAPE_OPTION_KEYS = ['style', 'location', 'color', 'text', 'textcolor', 'size', 'offset', 'tooltip', 'force_overlay', 'editable'] as const;\n\n/**\n * Draws a shape (triangle, arrow, circle, label...) on each bar where the condition is true: buy and sell signals.\n * @param condition - Series that is true (non-zero) on the bars that get a shape. With `location.absolute`, its\n * value is the price of the shape.\n * @param title - Name of the shapes in the settings and the alerts. Default: \"Shapes\".\n * @param options - Shape (`shape.*`), place (`location.*`), colour, text, size (`size.*`), offset... Default: `{}`\n * (a cross above the bar).\n * @example\n * ```js\n * const up = ta.crossover(ta.ema(close, 9), ta.ema(close, 21));\n * plotshape(up, \"Buy\", { style: shape.triangleup, location: location.belowbar, color: color.green });\n * ```\n */\nexport function plotshape(condition: Series, title?: string, options: PlotShapeOptions = {}): void {\n checkOptions('plotshape', options, SHAPE_OPTION_KEYS, ['color', 'textcolor']);\n emitMarkers('shape', condition, title, options);\n}\n\n/**\n * Draws a character (a letter, an emoji...) on each bar where the condition is true.\n * @param condition - Series that is true (non-zero) on the bars that get the character. With `location.absolute`,\n * its value is the price of the character.\n * @param title - Name of the characters in the settings and the alerts. Default: \"Chars\".\n * @param options - Character (`char`), place (`location.*`), colour, text, size (`size.*`), offset... Default: `{}`\n * (a star above the bar).\n * @example\n * ```js\n * const gapUp = open.gt(high.offset(1));\n * plotchar(gapUp, \"Gap up\", { char: \"\u25B2\", location: location.abovebar, color: color.teal });\n * ```\n */\nexport function plotchar(condition: Series, title?: string, options: PlotCharOptions = {}): void {\n checkOptions('plotchar', options, [...SHAPE_OPTION_KEYS.filter((k) => k !== 'style'), 'char'], ['color', 'textcolor']);\n emitMarkers('char', condition, title, options);\n}\n\nexport interface PlotArrowOptions {\n /** Colour of the up arrows: one colour or one per bar. Default: #00FF00. */\n colorup?: string | Array<string | undefined>;\n /** Colour of the down arrows: one colour or one per bar. Default: #FF0000. */\n colordown?: string | Array<string | undefined>;\n /** Moves the arrows by this many bars (the arrow of bar i is drawn on bar i + offset). Default: 0. */\n offset?: number;\n /** Height of the smallest arrow, in pixels. Default: 5. */\n minheight?: number;\n /** Height of the largest arrow, in pixels. Default: 100. */\n maxheight?: number;\n /** Where the arrows are shown: `display.all`, `display.none`... Default: everywhere. */\n display?: ArrowConfig['display'];\n /** Draw on the main chart pane even when the script is not an overlay (PineScript `force_overlay`); default false. */\n force_overlay?: boolean;\n /** False: not listed in the Style settings of the study (PineScript `editable`); default true. */\n editable?: boolean;\n}\n\n/**\n * Draws an up arrow below the bar where the value is positive and a down arrow above it where it is negative;\n * nothing for 0 or na. The larger the value, the longer the arrow (between `minheight` and `maxheight`).\n * @param series - Series whose sign gives the arrow's direction and whose size gives its length.\n * @param title - Name of the arrows in the settings and the alerts. Default: \"Arrows\".\n * @param options - Colours, heights, offset, display. Default: `{}` (green up, red down).\n * @example\n * ```js\n * const change = close.sub(close.offset(1));\n * plotarrow(change, \"Change\", { colorup: color.teal, colordown: color.orange });\n * ```\n */\nexport function plotarrow(series: Series, title?: string, options: PlotArrowOptions = {}): void {\n if (intrabarRun) return; // dropped: an intrabar run's outputs aren't read\n const c = collector();\n const id = `arrow${c.arrowConfig.length}`;\n title ??= DEFAULT_OUTPUT_TITLES.arrow;\n const pick = (col: string | Array<string | undefined> | undefined, fallback: string, i: number): string | undefined =>\n col === undefined ? fallback : typeof col === 'string' ? col : col[i];\n const colorup = typeof options.colorup === 'string' ? options.colorup : '#00FF00';\n const colordown = typeof options.colordown === 'string' ? options.colordown : '#FF0000';\n c.arrowConfig.push({\n id,\n title,\n colorup,\n colordown,\n minheight: options.minheight ?? 5,\n maxheight: options.maxheight ?? 100,\n offset: options.offset,\n display: options.display,\n forceOverlay: options.force_overlay,\n ...(options.editable === false ? { editable: false } : {}),\n });\n c.outputs.push({ kind: 'arrow', id, title });\n const values = series.toArray();\n const b = bars();\n const off = options.offset ?? 0;\n c.outputValues[id] = outputSeries(values, b);\n for (let i = 0; i < b.length; i++) {\n const v = values[i];\n if (v === undefined || Number.isNaN(v) || v === 0) continue;\n const j = i + off;\n if (j < 0 || j >= b.length) continue;\n const color = v > 0 ? pick(options.colorup, '#00FF00', i) : pick(options.colordown, '#FF0000', i);\n if (color === undefined) continue; // na color: no arrow\n c.arrows.push({ time: b[j]!.time, id, value: v, color });\n }\n}\n\n/** Shared emitter for bgcolor()/barcolor(). A static color applies to every\n * bar; a per-bar array (from color.when) skips undefined entries. The offset\n * is baked in: the color computed at bar i lands on bar i + offset. */\nfunction emitBarColors(\n kind: 'bgcolor' | 'barcolor',\n colors: string | Array<string | undefined>,\n options: { offset?: number; title?: string; force_overlay?: boolean; editable?: boolean }\n): void {\n if (intrabarRun) return; // dropped: an intrabar run's outputs aren't read\n const c = collector();\n const id = `${kind}${c.barColorConfig.filter((x) => x.kind === kind).length}`;\n c.barColorConfig.push({\n id,\n kind,\n title: options.title ?? DEFAULT_OUTPUT_TITLES[kind],\n offset: options.offset,\n forceOverlay: options.force_overlay,\n // a constant colour is a palette of one colour (PineScript); per-bar colours from constants keep theirs\n ...(typeof colors === 'string' ? { palette: [colors] } : paletteOfColors(colors) ? { palette: paletteOfColors(colors) } : {}),\n ...(options.editable === false ? { editable: false } : {}),\n outputIndex: c.outputs.length,\n });\n const b = bars();\n const off = options.offset ?? 0;\n const target: BgColorData[] = kind === 'bgcolor' ? c.bgColors : c.barColors;\n const forceOverlay = kind === 'bgcolor' && options.force_overlay === true;\n for (let i = 0; i < b.length; i++) {\n const col = typeof colors === 'string' ? colors : colors[i];\n if (!col) continue;\n const j = i + off;\n if (j < 0 || j >= b.length) continue;\n target.push(forceOverlay ? { time: b[j]!.time, color: col, id, forceOverlay } : { time: b[j]!.time, color: col, id });\n }\n}\n\n/**\n * Colours the background of the script's pane behind each bar.\n * @param colors - One colour for every bar, or one per bar from `color.when()` (no colour on an na entry).\n * @param options - `offset` (bars to move the colours by), `title` (default \"Background Color\"), `force_overlay`\n * (true: colour the price chart's pane), `editable`. Default: `{}`.\n * @example\n * ```js\n * const rsi = ta.rsi(close, 14);\n * bgcolor(color.when(rsi.gt(70), color.new(color.red, 85)));\n * ```\n */\nexport function bgcolor(\n colors: string | Array<string | undefined>,\n options: { offset?: number; title?: string; force_overlay?: boolean; editable?: boolean } = {}\n): void {\n if (ctx?.strict) checkColor('bgcolor(): the colour', colors);\n checkOptions('bgcolor', options, ['offset', 'title', 'force_overlay', 'editable']);\n emitBarColors('bgcolor', colors, options);\n}\n\n/**\n * Colours the chart's candles or bars, replacing their usual colours.\n * @param colors - One colour for every bar, or one per bar from `color.when()` (usual colour on an na entry).\n * @param options - `title` (default \"Bar Color\") and `editable`. Default: `{}`.\n * @example\n * ```js\n * const trendUp = close.gt(ta.sma(close, 50));\n * barcolor(color.when(trendUp, color.green, color.red));\n * ```\n */\nexport function barcolor(\n colors: string | Array<string | undefined>,\n options: { title?: string; editable?: boolean } = {}\n): void {\n if (ctx?.strict) checkColor('barcolor(): the colour', colors);\n checkOptions('barcolor', options, ['title', 'editable']);\n emitBarColors('barcolor', colors, options);\n}\n\n/** A colour argument of plotcandle() / plotbar(): a colour, or per-bar colours (null / undefined entries are na). */\nexport type ScriptCandleColor = string | Array<string | null | undefined>;\n\nexport interface PlotCandleOptions {\n /** Body colour: one colour or one per bar (`color.when()`); an na entry gives a see-through body. Default: #2962FF. */\n color?: ScriptCandleColor;\n /** Wick colour: one colour or one per bar. Default: #737375. */\n wickcolor?: ScriptCandleColor;\n /** Border colour: one colour or one per bar. Default: #000000. */\n bordercolor?: ScriptCandleColor;\n /** Where the candles are shown: `display.all`, `display.none`... Default: everywhere. */\n display?: CandleConfig['display'];\n /** Draw on the main chart pane even when the script is not an overlay (PineScript `force_overlay`); default false. */\n force_overlay?: boolean;\n /** False: not listed in the Style settings of the study (PineScript `editable`); default true. */\n editable?: boolean;\n}\n\nexport interface PlotBarOptions {\n /** Bar colour: one colour or one per bar (`color.when()`); an na entry gives a see-through bar. Default: #2962FF. */\n color?: ScriptCandleColor;\n /** Where the bars are shown: `display.all`, `display.none`... Default: everywhere. */\n display?: CandleConfig['display'];\n /** Draw on the main chart pane even when the script is not an overlay (PineScript `force_overlay`); default false. */\n force_overlay?: boolean;\n /** False: not listed in the Style settings of the study (PineScript `editable`); default true. */\n editable?: boolean;\n}\n\n/** Colour of bar i: undefined when the argument is not given, 'transparent' for an na entry. */\nfunction candleColor(col: ScriptCandleColor | undefined, i: number): string | undefined {\n if (col === undefined) return undefined;\n if (typeof col === 'string') return col;\n return col[i] ?? 'transparent';\n}\n\ninterface OhlcRow {\n i: number;\n open: number;\n high: number;\n low: number;\n close: number;\n}\n\n/** The bars where open, high, low and close are all not na (PineScript draws no candle / bar otherwise). */\nfunction ohlcRows(o: Series, h: Series, l: Series, cl: Series): OhlcRow[] {\n const [ov, hv, lv, cv] = [o.toArray(), h.toArray(), l.toArray(), cl.toArray()];\n const rows: OhlcRow[] = [];\n for (let i = 0; i < bars().length; i++) {\n const [open, high, low, close] = [ov[i]!, hv[i]!, lv[i]!, cv[i]!];\n if (Number.isFinite(open) && Number.isFinite(high) && Number.isFinite(low) && Number.isFinite(close)) {\n rows.push({ i, open, high, low, close });\n }\n }\n return rows;\n}\n\nconst staticColor = (col: ScriptCandleColor | undefined): string | undefined => (typeof col === 'string' ? col : undefined);\n\n/**\n * Colours of a plotcandle / plotbar argument left out, as the PineScript compiler declares them and the chart draws\n * them (reference: body / bar #2962FF, wick #737375, border #000000; the wick and border do not follow the body).\n */\nexport const DEFAULT_CANDLE_COLORS = {\n /** Body colour (and the colour of `plotbar()` bars). */\n color: '#2962FF',\n /** Wick colour. */\n wickColor: '#737375',\n /** Border colour. */\n borderColor: '#000000',\n} as const;\n\n/** The palettes of the per-bar colour arguments of a plotcandle / plotbar that have one. */\nfunction candlePalettes(cols: { color?: ScriptCandleColor; wickColor?: ScriptCandleColor; borderColor?: ScriptCandleColor }): { palettes?: CandleConfig['palettes'] } {\n const palettes: NonNullable<CandleConfig['palettes']> = {};\n for (const k of ['color', 'wickColor', 'borderColor'] as const) {\n const pal = paletteOfColors(cols[k]);\n if (pal) palettes[k] = pal;\n }\n return Object.keys(palettes).length ? { palettes } : {};\n}\n\n/** A colour argument, or the default when it is left out. */\nconst orDefault = (col: ScriptCandleColor | undefined, fallback: string): ScriptCandleColor => (col === undefined ? fallback : col);\n\n/**\n * Draws candles from four Series (for example the candles of another symbol, or smoothed prices). A bar where one of\n * the four values is na has no candle.\n * @param open - Open of each candle.\n * @param high - High of each candle.\n * @param low - Low of each candle.\n * @param close - Close of each candle.\n * @param title - Name of the candles in the settings. Default: \"PlotCandle\".\n * @param options - Body, wick and border colours, display, force_overlay, editable. Default: `{}`.\n * @example\n * ```js\n * const o = ta.ema(open, 5), h = ta.ema(high, 5), l = ta.ema(low, 5), c = ta.ema(close, 5);\n * plotcandle(o, h, l, c, \"Smoothed\", { color: color.when(c.gt(o), color.teal, color.red) });\n * ```\n */\nexport function plotcandle(\n open: Series,\n high: Series,\n low: Series,\n close: Series,\n title?: string,\n options: PlotCandleOptions = {}\n): void {\n if (intrabarRun) return; // dropped: an intrabar run's outputs aren't read\n const c = collector();\n const color = orDefault(options.color, DEFAULT_CANDLE_COLORS.color);\n const wickcolor = orDefault(options.wickcolor, DEFAULT_CANDLE_COLORS.wickColor);\n const bordercolor = orDefault(options.bordercolor, DEFAULT_CANDLE_COLORS.borderColor);\n const id = `plotcandle${c.candleConfig.filter((x) => x.kind === 'candle').length}`;\n title ??= DEFAULT_OUTPUT_TITLES.candle;\n c.candleConfig.push({\n id,\n kind: 'candle',\n title,\n color: staticColor(color),\n wickColor: staticColor(wickcolor),\n borderColor: staticColor(bordercolor),\n ...candlePalettes({ color, wickColor: wickcolor, borderColor: bordercolor }),\n display: options.display,\n forceOverlay: options.force_overlay,\n ...(options.editable === false ? { editable: false } : {}),\n });\n c.outputs.push({ kind: 'candle', id, title });\n const b = bars();\n c.plotCandles[id] = ohlcRows(open, high, low, close).map(({ i, ...ohlc }) => {\n const candle: PlotCandleData = { time: b[i]!.time, ...ohlc };\n const body = candleColor(color, i);\n const wickColor = candleColor(wickcolor, i);\n const borderColor = candleColor(bordercolor, i);\n if (body !== undefined) candle.color = body;\n if (wickColor !== undefined) candle.wickColor = wickColor;\n if (borderColor !== undefined) candle.borderColor = borderColor;\n if (options.force_overlay) candle.forceOverlay = true;\n return candle;\n });\n}\n\n/**\n * Draws open-high-low-close bars from four Series. A bar where one of the four values is na is not drawn.\n * @param open - Open of each bar.\n * @param high - High of each bar.\n * @param low - Low of each bar.\n * @param close - Close of each bar.\n * @param title - Name of the bars in the settings. Default: \"PlotBar\".\n * @param options - Colour, display, force_overlay, editable. Default: `{}`.\n * @example\n * ```js\n * plotbar(open, high, low, close, \"Bars\", { color: color.when(close.gt(open), color.green, color.red) });\n * ```\n */\nexport function plotbar(\n open: Series,\n high: Series,\n low: Series,\n close: Series,\n title?: string,\n options: PlotBarOptions = {}\n): void {\n if (intrabarRun) return; // dropped: an intrabar run's outputs aren't read\n const c = collector();\n const barColor = orDefault(options.color, DEFAULT_CANDLE_COLORS.color);\n const id = `plotbar${c.candleConfig.filter((x) => x.kind === 'bar').length}`;\n title ??= DEFAULT_OUTPUT_TITLES.bar;\n c.candleConfig.push({\n id,\n kind: 'bar',\n title,\n color: staticColor(barColor),\n ...candlePalettes({ color: barColor }),\n display: options.display,\n forceOverlay: options.force_overlay,\n ...(options.editable === false ? { editable: false } : {}),\n });\n c.outputs.push({ kind: 'bar', id, title });\n const b = bars();\n c.plotBars[id] = ohlcRows(open, high, low, close).map(({ i, ...ohlc }) => {\n const bar: PlotBarData = { time: b[i]!.time, ...ohlc };\n const color = candleColor(barColor, i);\n if (color !== undefined) bar.color = color;\n if (options.force_overlay) bar.forceOverlay = true;\n return bar;\n });\n}\n\n// \u2500\u2500 Per-bar execution (eachBar) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * The scalar view of one bar handed to an {@link eachBar} callback.\n * All fields are plain numbers, so native JS operators work.\n */\nexport interface BarContext {\n /** Bar index (PineScript bar_index). */\n readonly i: number;\n /** Total number of bars. */\n readonly n: number;\n /** Time of the current bar. */\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 /** Value of any Series at the current bar minus `offset` (PineScript src[offset]). */\n get(src: Series, offset?: number): number;\n /** This block's own previous output (PineScript self-reference, offset >= 1). */\n prev(offset?: number): number;\n}\n\n/**\n * Runs the callback once per bar, in order, and collects the returned values\n * into a Series. This is the escape hatch for PineScript logic the vectorized\n * model cannot express:\n *\n * - `var x = 0` / `x := ...` \u2192 a plain `let` variable captured by the closure\n * - per-bar `if` / `for` / `while` \u2192 native JS statements\n * - `src[k]` \u2192 `c.get(src, k)`; self-reference \u2192 `c.prev()`\n *\n * Returning a boolean collects 1/0; returning nothing collects na (NaN).\n *\n * ```typescript\n * let dir = 0; // var dir = 0\n * const trend = eachBar((c) => {\n * if (c.close > c.get(close, 1)) dir = 1; // dir := 1\n * else if (c.close < c.get(close, 1)) dir = -1;\n * return dir;\n * });\n * ```\n */\n/** Initial history buffer of a script series and its growth factor (measured, issue #149). */\nconst HISTORY_START = 242;\nconst HISTORY_GROWTH = 1.618034;\n\n/**\n * History buffer of one script series in eachBar(), as PineScript grows it (measured on PineScript, issue #149):\n * the buffer starts with 242 bars; when the largest reference of a bar goes past it, a jump (the reference grew by\n * more than 1 since the previous bar) sets the buffer to the reference, and a step of 1 grows it to\n * round(size * 1.618034); a buffer above 5000 stops the script on the next bar (RE10008), with that size as\n * \"bars back\". A reference above 5000 stops it at once.\n */\ninterface HistoryBuffer {\n size: number;\n previous: number;\n barMax: number;\n}\n\n/** The outer variables an eachBar() callback changes, by callback source (the same callback on every run). */\nconst outerWritesCache = new Map<string, string[]>();\nfunction outerWritesOf(fn: (...args: never[]) => unknown): string[] {\n const src = fn.toString();\n let found = outerWritesCache.get(src);\n if (!found) {\n found = outerWrites(src);\n if (outerWritesCache.size > 500) outerWritesCache.clear();\n outerWritesCache.set(src, found);\n }\n return found;\n}\n\n/**\n * Runs a function on every bar, oldest first, for logic that needs the bar's values one at a time (state, ifs,\n * loops). The function reads the bar through `c` (`c.close`, `c.get(series)`, `c.get(series, 1)` for one bar back)\n * and returns the bar's value of the Series that `eachBar` gives back (na when it returns nothing).\n * @param fn - Called once per bar with the bar's context; returns a number (or true / false) for that bar.\n * @returns Series of the values the function returned.\n * @example\n * ```js\n * const fast = ta.sma(close, 10);\n * let count = 0;\n * const streak = eachBar((c) => (count = c.get(close) > c.get(fast) ? count + 1 : 0));\n * plot(streak, \"Bars above\");\n * ```\n */\nexport function eachBar(fn: (c: BarContext) => number | boolean | void): Series {\n return runBlock(fn);\n}\n\n/** State an eachBar() block keeps in its incremental checkpoint besides the script's (the strategy engine). */\ninterface BlockExtra {\n save(): unknown;\n restore(state: unknown): void;\n}\n\nfunction runBlock(\n fn: (c: BarContext) => number | boolean | void,\n extra?: BlockExtra,\n /** The script's own callback, when fn wraps it (strategy.eachBar) */\n own: (c: BarContext) => number | boolean | void = fn\n): Series {\n collector(); // same lifecycle guard (and error message) as the declaration calls\n const b = bars();\n // An intrabar run ends on its bar: the chart's last bar stays the main run's.\n const lastIndex = intrabarRun ? intrabarRun.lastBarIndex : b.length - 1;\n let out: number[] = [];\n const cache = new Map<Series, number[]>();\n // history buffers by source: the slot of a Series made by the script (matched across incremental runs), or the Series\n const buffers = new Map<unknown, HistoryBuffer>();\n const bufferKey = (src: Series): unknown => incremental.slotOf(src) ?? src;\n let pendingError: { bar: number; barsBack: number } | null = null;\n let idx = 0;\n\n // An incremental run (#196): the block is matched by its order with the previous run; a resumed block starts on the\n // forming bar of the previous run, from its state at the end of the last confirmed bar.\n const run = incremental.active;\n const slot = run ? (run.block < 0 ? run.blockSlot++ : -1) : -1;\n if (run && slot < 0) incremental.nonIncremental('eachBar() inside eachBar()');\n if (run?.mode === 'record') {\n // a variable outside the callback that it changes is not put back by a resumed run: use persist()\n const written = outerWritesOf(own);\n if (written.length) incremental.nonIncremental(`eachBar() callback changes ${written.join(', ')} outside it (use persist())`);\n }\n let start = 0;\n let checkpoint: incremental.BlockCheckpoint | null = null;\n if (run?.mode !== 'resume') out = new Array(b.length).fill(NaN);\n else {\n const prev = run.prev?.blocks[slot];\n if (!prev) incremental.nonIncremental('a new eachBar() block');\n start = run.from;\n // the block's own array of the previous run: its first values are kept in place\n out = prev!.out;\n out.length = b.length;\n for (let i = start; i < b.length; i++) out[i] = NaN;\n checkpoint = prev!.checkpoint;\n // the block that draws puts the registry back to the last confirmed bar\n if (run.prev!.drawingBlock === slot && checkpoint.drawings) restoreDrawingCheckpoint(checkpoint.drawings);\n if (extra) extra.restore(checkpoint.extra);\n for (const [key, state] of checkpoint.buffers) buffers.set(key, { ...state });\n pendingError = checkpoint.pendingError ? { ...checkpoint.pendingError } : null;\n for (const [box, value] of checkpoint.boxes) {\n const ref = run.boxes[box];\n if (!ref) incremental.nonIncremental('a persist() box of the previous run is missing');\n ref!.set(incremental.copyValue(value));\n }\n }\n /** State at the end of the bar just run: the boxes this block owns, the history buffers */\n const takeCheckpoint = (): incremental.BlockCheckpoint => {\n const boxes = new Map<number, unknown>();\n run!.boxes.forEach((ref, box) => {\n if (run!.next.boxOwner[box] === slot) boxes.set(box, incremental.copyValue(ref.get()));\n });\n const kept = new Map<unknown, HistoryBuffer>();\n for (const [key, state] of buffers) kept.set(key, { ...state });\n return {\n boxes,\n buffers: kept,\n pendingError: pendingError ? { ...pendingError } : null,\n drawings: saveDrawingCheckpoint(),\n extra: extra?.save(),\n };\n };\n // the last confirmed bar is before the first bar run (a new run of one bar): its state is the initial one\n if (run && b.length - 2 < start && !checkpoint) checkpoint = takeCheckpoint();\n\n const ctx: BarContext = {\n get i() {\n return idx;\n },\n get n() {\n // the bar count changes with each new bar: a value read from it is not kept by an incremental run (the chart's\n // last bar of the intrabar runs of a backtest does not change)\n if (run && !intrabarRun) incremental.nonIncremental('BarContext.n');\n return lastIndex + 1;\n },\n get time() {\n return b[idx]!.time as number;\n },\n get open() {\n return b[idx]!.open;\n },\n get high() {\n return b[idx]!.high;\n },\n get low() {\n return b[idx]!.low;\n },\n get close() {\n return b[idx]!.close;\n },\n get volume() {\n return b[idx]!.volume ?? NaN;\n },\n get(src: Series, offset: number = 0): number {\n if (offset < 0) throw new RangeError(`c.get(): the offset cannot be negative (${offset} would read a future bar).`);\n if (!src.fullHistory && offset > 0) {\n const k = Math.floor(offset);\n if (k > MAX_BARS_BACK) throw new Error(historyError(idx, k));\n let buffer = buffers.get(bufferKey(src));\n if (!buffer) buffers.set(bufferKey(src), (buffer = { size: HISTORY_START, previous: 0, barMax: 0 }));\n if (k > buffer.barMax) buffer.barMax = k;\n }\n let vals = cache.get(src);\n if (!vals) {\n vals = src.toArray();\n cache.set(src, vals);\n }\n const j = idx - offset;\n return j >= 0 && j < vals.length ? (vals[j] ?? NaN) : NaN;\n },\n prev(offset: number = 1): number {\n const j = idx - Math.max(1, offset);\n return j >= 0 ? out[j]! : NaN;\n },\n };\n const outerBlock = run ? run.block : -1;\n if (run) run.block = slot;\n try {\n for (idx = start; idx < b.length; idx++) {\n if (pendingError && pendingError.bar === idx) throw new Error(historyError(idx, pendingError.barsBack));\n currentBar = idx;\n setDrawingBar(idx, idx === lastIndex, lastIndex);\n const r = fn(ctx);\n out[idx] = typeof r === 'number' ? r : typeof r === 'boolean' ? (r ? 1 : 0) : NaN;\n // grow the history buffers from the largest reference of this bar\n for (const buffer of buffers.values()) {\n const k = buffer.barMax;\n if (k > buffer.size) {\n const next = k - buffer.previous > 1 ? k : Math.round(buffer.size * HISTORY_GROWTH);\n if (next > MAX_BARS_BACK && !pendingError) pendingError = { bar: idx + 1, barsBack: next };\n buffer.size = next;\n }\n buffer.previous = k;\n buffer.barMax = 0;\n }\n // the last confirmed bar (the forming bar is the last one): its state is where the next update starts\n if (run && idx === b.length - 2) checkpoint = takeCheckpoint();\n }\n } finally {\n currentBar = -1;\n setDrawingBar(null);\n if (run) run.block = outerBlock;\n }\n if (run) run.next.blocks[slot] = { out, checkpoint: checkpoint! };\n return Series.fromArray(ctxBars, out);\n}\n\n/** Bar index of the running eachBar() callback, -1 outside eachBar(). */\nlet currentBar = -1;\n\n// \u2500\u2500 Strategy (declaration and strategy.* API; the host supplies the order engine) \u2500\u2500\n\n/** The strategy of the current run; throws when the script did not declare strategy(). */\nfunction strategyRun(caller: string): StrategyRun {\n const run = collector().strategy;\n if (!run) throw new Error(`${caller}: declare the script with strategy() first.`);\n return run;\n}\n\nfunction strategyEngine(caller: string): StrategyEngine {\n const run = strategyRun(caller);\n if (!run.engine) {\n throw new Error(\n `${caller}: no strategy engine; pass it as executeScript(body, bars, inputs, chart, { strategyEngine }).`\n );\n }\n return run.engine;\n}\n\n/** The engine for an order call: order calls run inside strategy.eachBar(), at a bar close. */\nfunction orderEngine(caller: string): StrategyEngine {\n const engine = strategyEngine(caller);\n if (!strategyRun(caller).inLoop) throw new Error(`${caller} must be called inside strategy.eachBar().`);\n return engine;\n}\n\n/** Options without na (NaN) numbers and undefined values: in PineScript an na argument means \"not given\". */\nfunction given<T extends object>(options: T): T {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(options)) {\n if (value === undefined || (typeof value === 'number' && Number.isNaN(value))) continue;\n out[key] = value;\n }\n return out as T;\n}\n\n/** The engine for a `strategy.*` read: the values are per bar, so they are read inside strategy.eachBar(). */\nfunction readEngine(caller: string): StrategyEngine {\n const engine = strategyEngine(caller);\n if (!strategyRun(caller).inLoop) throw new Error(`${caller} must be read inside strategy.eachBar().`);\n return engine;\n}\n\n/** `strategy.*` variables that do not change from bar to bar, readable anywhere in the script. */\nconst STRATEGY_CONSTANT_VARIABLES: ReadonlySet<StrategyVariable> = new Set(['initial_capital', 'account_currency']);\n\nfunction strategyVariable(name: StrategyVariable): number | string {\n const caller = `strategy.${name}`;\n const engine = STRATEGY_CONSTANT_VARIABLES.has(name) ? strategyEngine(caller) : readEngine(caller);\n const value = engine.get(name);\n if (value === undefined) throw new Error(`strategy.${name} is not provided by the strategy engine.`);\n return value;\n}\n\nfunction riskRule(rule: StrategyRiskRule): void {\n if (intrabarRun) return; // declared by the main run\n const engine = strategyEngine(`strategy.risk.${rule.rule}()`);\n if (!engine.risk) throw new Error(`strategy.risk.${rule.rule}() is not provided by the strategy engine.`);\n engine.risk(rule);\n}\n\n/** PineScript `strategy()` declaration: script metadata and strategy properties. */\nfunction declareStrategy(title: string, options: StrategyOptions = {}): void {\n const c = collector();\n declare(c, 'strategy');\n c.title = title;\n c.shortTitle = options.shorttitle;\n c.overlay = options.overlay ?? false;\n c.precision = options.precision;\n c.format = options.format;\n setDrawingLimits({\n line: options.max_lines_count,\n label: options.max_labels_count,\n box: options.max_boxes_count,\n polyline: options.max_polylines_count,\n });\n const properties: StrategyProperties = { ...STRATEGY_DEFAULTS };\n const target = properties as unknown as Record<string, unknown>;\n for (const key of [...Object.keys(STRATEGY_DEFAULTS), 'currency']) {\n const value = (options as Record<string, unknown>)[key];\n if (value !== undefined) target[key] = value;\n }\n const factory = scriptOptions.strategyEngine;\n c.strategy = {\n properties,\n engine: factory?.({ properties, bars: ctxBars.bars, chart: chartCtx }),\n looped: false,\n inLoop: false,\n };\n}\n\n/**\n * Runs the strategy logic once per bar, in order, like {@link eachBar}. On each bar the engine first\n * fills the pending orders (`processBar`), then the callback runs at the bar close (order calls,\n * `strategy.*` variables), then `processClose` runs. A script has one strategy.eachBar() per run.\n * The callback's return values are collected into a Series, as with eachBar().\n */\nfunction strategyEachBar(fn: (c: BarContext) => number | boolean | void): Series {\n const run = strategyRun('strategy.eachBar()');\n const engine = strategyEngine('strategy.eachBar()');\n if (run.looped) throw new Error('strategy.eachBar() runs once per script run.');\n run.looped = true;\n const intrabar = intrabarRun;\n if (intrabar) {\n // Intrabar run: the bars before replay the main run's answers, the bar itself calls the engine (whose\n // orders the host is filling: no processBar / processClose).\n const varipState = varipRun;\n const replayLog: { answers: readonly unknown[]; next: number } = { answers: [], next: 0 };\n const replayed = replayEngine(replayLog);\n return runBlock((c) => {\n const replay = c.i < intrabar.bar;\n if (replay) {\n replayLog.answers = intrabar.recorder.answers[c.i] ?? [];\n replayLog.next = 0;\n }\n run.engine = replay ? replayed : intrabar.engine;\n varipState.mode = replay ? 'replay' : 'live';\n const starts = replay ? intrabar.recorder.varipStarts[c.i] ?? intrabar.recorder.varip : null;\n varipState.scratch = starts ? (starts.length ? [...starts] : NO_VARIP) : null;\n run.inLoop = true;\n try {\n return fn(c);\n } finally {\n run.inLoop = false;\n run.engine = intrabar.engine;\n varipState.mode = 'live';\n varipState.scratch = null;\n }\n }, undefined, fn);\n }\n const recorder = scriptOptions.recorder;\n // an incremental run keeps the engine state at the last confirmed bar: the engine has to save and restore it\n if (incremental.active) {\n if (recorder) incremental.nonIncremental('a strategy with intrabar runs (recorder)');\n if (!engine.save || !engine.restore) incremental.nonIncremental('a strategy engine without save() / restore()');\n }\n const extra: BlockExtra | undefined =\n engine.save && engine.restore ? { save: () => engine.save!(), restore: (s) => engine.restore!(s) } : undefined;\n return runBlock((c) => {\n engine.processBar(c.i);\n if (recorder) {\n recorder.varipStarts[c.i] = [...recorder.varip];\n run.engine = recordingEngine(engine, (recorder.answers[c.i] = []));\n }\n run.inLoop = true;\n try {\n return fn(c);\n } finally {\n run.inLoop = false;\n run.engine = engine;\n engine.processClose(c.i);\n }\n }, extra, fn);\n}\n\n/** The engine of a main run that records its answers (see {@link StrategyRecorder}). */\nfunction recordingEngine(engine: StrategyEngine, log: unknown[]): StrategyEngine {\n const keep = <T>(v: T): T => {\n log.push(v);\n return v;\n };\n return {\n ...forward(engine),\n get: (name) => keep(engine.get(name)),\n openTrade: (index) => keep(engine.openTrade(index)),\n closedTrade: (index) => keep(engine.closedTrade(index)),\n defaultEntryQty: engine.defaultEntryQty ? (price) => keep(engine.defaultEntryQty!(price)) : undefined,\n };\n}\n\n/** An engine that gives back recorded answers in order and drops the order calls (a replayed bar). */\nfunction replayEngine(log: { answers: readonly unknown[]; next: number }): StrategyEngine {\n const next = <T>(): T => log.answers[log.next++] as T;\n const none = (): void => {};\n return {\n processBar: none,\n processClose: none,\n entry: none,\n order: none,\n exit: none,\n close: none,\n close_all: none,\n cancel: none,\n cancel_all: none,\n risk: none,\n get: () => next(),\n openTrade: () => next(),\n closedTrade: () => next(),\n defaultEntryQty: () => next(),\n };\n}\n\n/** The calls of `engine`, bound to it. */\nfunction forward(engine: StrategyEngine): StrategyEngine {\n return {\n processBar: (bar) => engine.processBar(bar),\n processClose: (bar) => engine.processClose(bar),\n entry: (id, direction, options) => engine.entry(id, direction, options),\n order: (id, direction, options) => engine.order(id, direction, options),\n exit: (id, options) => engine.exit(id, options),\n close: (id, options) => engine.close(id, options),\n close_all: (options) => engine.close_all(options),\n cancel: (id) => engine.cancel(id),\n cancel_all: () => engine.cancel_all(),\n risk: engine.risk ? (rule) => engine.risk!(rule) : undefined,\n get: (name) => engine.get(name),\n openTrade: (index) => engine.openTrade(index),\n closedTrade: (index) => engine.closedTrade(index),\n defaultEntryQty: engine.defaultEntryQty ? (price) => engine.defaultEntryQty!(price) : undefined,\n };\n}\n\n/** Numeric `strategy.*` variables, read from the engine (current bar inside strategy.eachBar()). */\nexport type StrategyNumberVariables = { readonly [K in StrategyNumberVariable]: number };\n/** Text `strategy.*` variables, read from the engine. */\nexport type StrategyTextVariables = { readonly [K in StrategyTextVariable]: string };\n\n/** PineScript `strategy`: the `strategy()` declaration and the `strategy.*` namespace. */\nexport type StrategyApi = ((title: string, options?: StrategyOptions) => void) &\n typeof STRATEGY_CONSTANTS &\n StrategyNumberVariables &\n StrategyTextVariables & {\n eachBar: typeof strategyEachBar;\n entry(id: string, direction: StrategyDirection, options?: StrategyEntryOptions): void;\n order(id: string, direction: StrategyDirection, options?: StrategyEntryOptions): void;\n exit(id: string, options?: StrategyExitOptions): void;\n close(id: string, options?: StrategyCloseOptions): void;\n close_all(options?: StrategyCloseAllOptions): void;\n cancel(id: string): void;\n cancel_all(): void;\n /** PineScript `strategy.opentrades.*(index)`: open trade `index` (0 = oldest), undefined when it does not exist. */\n opentrade(index: number): StrategyTrade | undefined;\n /** PineScript `strategy.closedtrades.*(index)`: closed trade `index` (0 = oldest), undefined when it does not exist. */\n closedtrade(index: number): StrategyTrade | undefined;\n default_entry_qty(fill_price: number): number;\n risk: {\n allow_entry_in(direction: StrategyRiskDirection): void;\n max_cons_loss_days(count: number, alert_message?: string): void;\n max_drawdown(value: number, type: StrategyRiskValueType, alert_message?: string): void;\n max_intraday_filled_orders(count: number, alert_message?: string): void;\n max_intraday_loss(value: number, type: StrategyRiskValueType, alert_message?: string): void;\n max_position_size(contracts: number): void;\n };\n };\n\nconst strategyMembers = {\n ...STRATEGY_CONSTANTS,\n eachBar: strategyEachBar,\n entry(id: string, direction: StrategyDirection, options: StrategyEntryOptions = {}): void {\n orderEngine('strategy.entry()').entry(id, direction, given(options));\n },\n order(id: string, direction: StrategyDirection, options: StrategyEntryOptions = {}): void {\n orderEngine('strategy.order()').order(id, direction, given(options));\n },\n exit(id: string, options: StrategyExitOptions = {}): void {\n orderEngine('strategy.exit()').exit(id, given(options));\n },\n close(id: string, options: StrategyCloseOptions = {}): void {\n orderEngine('strategy.close()').close(id, given(options));\n },\n close_all(options: StrategyCloseAllOptions = {}): void {\n orderEngine('strategy.close_all()').close_all(given(options));\n },\n cancel(id: string): void {\n orderEngine('strategy.cancel()').cancel(id);\n },\n cancel_all(): void {\n orderEngine('strategy.cancel_all()').cancel_all();\n },\n opentrade(index: number): StrategyTrade | undefined {\n return readEngine('strategy.opentrade()').openTrade(index);\n },\n closedtrade(index: number): StrategyTrade | undefined {\n return readEngine('strategy.closedtrade()').closedTrade(index);\n },\n default_entry_qty(fill_price: number): number {\n const engine = readEngine('strategy.default_entry_qty()');\n if (!engine.defaultEntryQty) throw new Error('strategy.default_entry_qty() is not provided by the strategy engine.');\n return engine.defaultEntryQty(fill_price);\n },\n risk: {\n allow_entry_in: (direction: StrategyRiskDirection) => riskRule({ rule: 'allow_entry_in', direction }),\n max_cons_loss_days: (count: number, alert_message?: string) =>\n riskRule(given({ rule: 'max_cons_loss_days' as const, count, alert_message })),\n max_drawdown: (value: number, type: StrategyRiskValueType, alert_message?: string) =>\n riskRule(given({ rule: 'max_drawdown' as const, value, type, alert_message })),\n max_intraday_filled_orders: (count: number, alert_message?: string) =>\n riskRule(given({ rule: 'max_intraday_filled_orders' as const, count, alert_message })),\n max_intraday_loss: (value: number, type: StrategyRiskValueType, alert_message?: string) =>\n riskRule(given({ rule: 'max_intraday_loss' as const, value, type, alert_message })),\n max_position_size: (contracts: number) => riskRule({ rule: 'max_position_size', contracts }),\n },\n};\n\nconst variableGetters: PropertyDescriptorMap = {};\nfor (const name of [...STRATEGY_NUMBER_VARIABLES, ...STRATEGY_TEXT_VARIABLES]) {\n variableGetters[name] = { get: () => strategyVariable(name), enumerable: true };\n}\n\n/**\n * PineScript `strategy`: call it to declare a strategy, and use its members as the `strategy.*` namespace.\n * OakScriptJS does not fill orders: the host passes an engine in `executeScript(..., { strategyEngine })`,\n * and the order calls and `strategy.*` variables are forwarded to it.\n *\n * ```typescript\n * strategy('MA Cross', { initial_capital: 10000, default_qty_type: strategy.percent_of_equity, default_qty_value: 100 });\n * const up = ta.crossover(ta.sma(close, 9), ta.sma(close, 21));\n * strategy.eachBar((c) => {\n * if (c.get(up) && strategy.position_size === 0) {\n * strategy.entry('L', strategy.long);\n * strategy.exit('X', { from_entry: 'L', stop: c.close * 0.95, limit: c.close * 1.15 });\n * }\n * });\n * ```\n */\nexport const strategy: StrategyNamespace = Object.defineProperties(\n Object.assign((title: string, options?: StrategyOptions) => declareStrategy(title, options), strategyMembers),\n variableGetters\n) as StrategyApi;\nsameKeys<StrategyApi, StrategyNamespace>(true);\nsameKeys<StrategyApi['risk'], StrategyNamespace['risk']>(true);\n\n/** Types of chart PineScript tells apart (`chart.is_*`); every other type is 'standard'. */\nexport type ChartType = 'standard' | 'heikinashi' | 'renko' | 'kagi' | 'linebreak' | 'pnf' | 'range';\n\n// \u2500\u2500 Chart context (issue #100) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * What the caller knows about the loaded bars. PineScript reads these values from the chart and\n * the symbol; nothing is fetched here. A script that needs a value the caller did not give throws.\n */\nexport interface ChartContext {\n /** Chart timeframe: \"5\", \"60\", \"1D\", \"1W\"... (PineScript `timeframe.period`) */\n timeframe?: string;\n /** Exchange time zone: \"America/New_York\", \"Etc/UTC\"... (PineScript `syminfo.timezone`) */\n timezone?: string;\n /** Session type of the bars (PineScript `syminfo.session`); default \"regular\" */\n sessionType?: 'regular' | 'extended';\n /**\n * Session of the loaded bars in the symbol session format: hours (\"0930-1600\", \"1700-1600\", \"24x7\"),\n * corrections (early closes, days off) and holidays. Needed by `time(tf)`, `time_close`,\n * `timeframe.change`, `time_tradingday`, `session.*` and the default anchor of `ta.vwap`.\n */\n session?: SessionSpec | string;\n /** Regular trading hours when the bars include extended hours (default: `session`); holidays default to `session`'s */\n regularSession?: SessionSpec | string;\n /** Chart symbol as PineScript `syminfo.tickerid` (e.g. \"NASDAQ:AAPL\"); needed by `request.security(syminfo.tickerid, ...)` */\n tickerid?: string;\n /** Unit of `Bar.time`: 's' (default, as lightweight-charts) or 'ms'. PineScript times are in ms. */\n timeUnit?: 's' | 'ms';\n /**\n * Minimum price move of the symbol (PineScript `syminfo.mintick`), e.g. 0.01; used by `math.round_to_mintick` and\n * `format.mintick`. Default: `minmove / pricescale` when both are given\n */\n mintick?: number;\n /**\n * PineScript `syminfo.minmove` and `syminfo.pricescale` (mintick = minmove / pricescale). Default: from `mintick`,\n * with pricescale 10^(its decimals) (0.25 is 25 / 100). Pass them for a symbol priced in fractions (1 / 32):\n * `format.mintick` shows floor(log10(pricescale)) decimals\n */\n minmove?: number;\n pricescale?: number;\n /** Currency value of one point of price move for one contract (PineScript `syminfo.pointvalue`); 1 for stocks */\n pointvalue?: number;\n /** Smallest tradable quantity (PineScript `syminfo.mincontract`); 1 for whole shares */\n mincontract?: number;\n /** Symbol type (PineScript `syminfo.type`): \"stock\", \"crypto\", \"forex\", \"futures\", \"index\", \"fund\"... */\n symbolType?: string;\n /** Currency of the symbol (PineScript `syminfo.currency`), e.g. \"USD\" */\n currency?: string;\n /**\n * Base currency of the symbol (PineScript `syminfo.basecurrency`): \"BTC\" for BITSTAMP:BTCUSD, BINANCE:BTCUSDT.P and\n * CME:BTC1!, \"EUR\" for FX:EURUSD, \"\" for a stock, an index or CME_MINI:ES1! (#180).\n *\n * The symbol fields below, like this one: a value; null when the symbol has none (PineScript gives na: \"\" for a\n * text, which `na()` takes as na, NaN for a number); left out when the host does not know it (reading it throws).\n */\n basecurrency?: string | null;\n /**\n * Root of the symbol (PineScript `syminfo.root`): \"BTC\" for CME:BTC1!, \"ES\" for CME_MINI:ES1!, \"AAPL\" for\n * NASDAQ:AAPL (#180). Default: the ticker, without the \"1!\" of a continuous future or the month code and year of a\n * contract (\"ESZ2026\" of a `symbolType` \"futures\").\n */\n root?: string | null;\n /** Description of the symbol (PineScript `syminfo.description`): \"Apple Inc.\" for NASDAQ:AAPL, \"Bitcoin / U.S. dollar\" for BITSTAMP:BTCUSD (#184) */\n description?: string | null;\n /** Prefix of the ticker id (PineScript `syminfo.prefix`), default: the part of `tickerid` before \":\" */\n prefix?: string | null;\n /** Ticker without its prefix (PineScript `syminfo.ticker`), default: the part of `tickerid` after \":\" */\n ticker?: string;\n /** The chart's own symbol (PineScript `syminfo.main_tickerid`, the same inside `request.security`); default `tickerid` */\n mainTickerid?: string;\n /** The chart's own timeframe (`timeframe.main_period`, the same inside `request.security`); default `timeframe` */\n mainTimeframe?: string;\n /** Two-letter code of the country the symbol trades in (PineScript `syminfo.country`): \"US\", \"IN\" */\n country?: string | null;\n /** Contract a continuous future stands for (PineScript `syminfo.current_contract`): \"ESZ2026\" for CME_MINI:ES1! */\n currentContract?: string | null;\n /** Last trading day of a future's contract, in ms (PineScript `syminfo.expiration_date`) */\n expirationDate?: number | null;\n /** PineScript `syminfo.sector` and `syminfo.industry` of a company */\n sector?: string | null;\n industry?: string | null;\n /** PineScript `syminfo.isin`: \"US0378331005\" for NASDAQ:AAPL */\n isin?: string | null;\n /** Unit of the volume (PineScript `syminfo.volumetype`): \"base\" (crypto: in the base currency), \"quote\", \"tick\", \"n/a\" */\n volumetype?: string | null;\n /** PineScript `syminfo.employees`, `syminfo.shareholders`, `syminfo.shares_outstanding_total` / `_float` */\n employees?: number | null;\n shareholders?: number | null;\n sharesOutstandingTotal?: number | null;\n sharesOutstandingFloat?: number | null;\n /** Analysts' ratings (PineScript `syminfo.recommendations_*`; `date` in ms) */\n recommendations?: SymbolRecommendations | null;\n /** Analysts' price targets (PineScript `syminfo.target_price_*`; `date` in ms) */\n targetPrice?: SymbolTargetPrice | null;\n /**\n * Dividends, splits and earnings of a symbol (PineScript `request.dividends`, `request.splits`, `request.earnings`,\n * `dividends.future_*`, `earnings.future_*`). Return undefined when they are not loaded: the run then ends with a\n * {@link MissingSymbolDataError} whose request has `events: true`. Return {} for a symbol without any.\n */\n events?: (symbol: string) => SymbolEvents | undefined;\n /** Chart foreground colour (PineScript `chart.fg_color`), e.g. \"#DBDBDB\" on a dark chart */\n foregroundColor?: string;\n /** Chart background colour (PineScript `chart.bg_color`), e.g. \"#0F0F0F\" on a dark chart */\n backgroundColor?: string;\n /**\n * Times (ms) of the first and the last bar in view (PineScript `chart.left_visible_bar_time` and\n * `chart.right_visible_bar_time`); default: the first and the last bar. A script that reads them\n * ({@link ScriptRunResult.usesVisibleRange}) has to be calculated again when they change.\n */\n leftVisibleBarTime?: number;\n rightVisibleBarTime?: number;\n /** Type of the chart (PineScript `chart.is_standard`, `chart.is_heikinashi`...); default 'standard' */\n chartType?: ChartType;\n /** Current time in ms (PineScript `timenow`); default: the clock of the computer at the start of the run */\n now?: number;\n /**\n * The last bar is closed (`barstate.isconfirmed` on the last bar). Default false: PineScript treats the last bar\n * of the data as not confirmed until the data feed closes it.\n */\n lastBarConfirmed?: boolean;\n /** The last bar receives live updates (`barstate.isrealtime`); default false (a calculation on history). */\n realtime?: boolean;\n /** On a realtime last bar: this run is the first update of the bar (`barstate.isnew`); default true. */\n lastBarNew?: boolean;\n /**\n * Bars of another symbol for `request.security(symbol, timeframe, ...)` (#179): the bars of `symbol` (the ticker id\n * as written in the script, e.g. \"NASDAQ:MSFT\") on `timeframe` (the chart timeframe for \"\"), oldest first, times in\n * `timeUnit`. Return undefined when they are not loaded: the run then ends with a {@link MissingSymbolDataError}\n * that lists every request, so the host can load them and run again. Return [] for a symbol that does not exist.\n */\n bars?: (symbol: string, timeframe: string) => Bar[] | undefined;\n /**\n * Calendar and properties of another symbol: its time zone and session give the close times and trading days that\n * `request.security` merges on (#179), and the other fields its `syminfo.*` inside the expression.\n */\n symbolInfo?: (symbol: string) => SymbolInfo | undefined;\n /**\n * Ticker of a seed data series for `request.seed(source, symbol, ...)` (#205), whose bars then come from\n * {@link bars} like any other symbol. Default: `\"<SOURCE>:<SYMBOL>\"` upper-cased.\n */\n seedSymbol?: (source: string, symbol: string) => string;\n}\n\n/** Calendar and properties of a symbol, as in {@link ChartContext}. */\nexport type SymbolInfo = Pick<\n ChartContext,\n | 'timezone'\n | 'session'\n | 'regularSession'\n | 'mintick'\n | 'minmove'\n | 'pricescale'\n | 'pointvalue'\n | 'mincontract'\n | 'symbolType'\n | 'currency'\n | 'basecurrency'\n | 'root'\n | 'description'\n | 'prefix'\n | 'ticker'\n | 'country'\n | 'currentContract'\n | 'expirationDate'\n | 'sector'\n | 'industry'\n | 'isin'\n | 'volumetype'\n | 'employees'\n | 'shareholders'\n | 'sharesOutstandingTotal'\n | 'sharesOutstandingFloat'\n | 'recommendations'\n | 'targetPrice'\n>;\n\n/** The symbol fields a {@link SymbolInfo} gives to `syminfo.*` inside `request.security`. */\nconst SYMBOL_INFO_KEYS = [\n 'timezone', 'session', 'regularSession', 'mintick', 'minmove', 'pricescale', 'pointvalue', 'mincontract', 'symbolType',\n 'currency', 'basecurrency', 'root', 'description', 'prefix', 'ticker', 'country', 'currentContract', 'expirationDate',\n 'sector', 'industry', 'isin', 'volumetype', 'employees', 'shareholders', 'sharesOutstandingTotal',\n 'sharesOutstandingFloat', 'recommendations', 'targetPrice',\n] as const satisfies readonly (keyof SymbolInfo)[];\n\n/** Analysts' ratings of a symbol: counts of each rating, and the date of the count (ms). */\nexport interface SymbolRecommendations {\n buy: number;\n buy_strong: number;\n hold: number;\n sell: number;\n sell_strong: number;\n total: number;\n date: number;\n}\n\n/** Analysts' price targets of a symbol, their number and the date of the figures (ms). */\nexport interface SymbolTargetPrice {\n average: number;\n high: number;\n low: number;\n median: number;\n estimates: number;\n date: number;\n}\n\n/**\n * A dividend: `time` the ex-date (ms; 00:00 UTC of the day, as PineScript's dividends are stamped), the amount per\n * share as declared (not adjusted for later splits), net and gross of withholding tax (gross defaults to net).\n */\nexport interface DividendEvent {\n time: number;\n net: number;\n gross?: number;\n /** Payment date (ms) */\n payDate?: number | null;\n}\n\n/** A split from `denominator` shares to `numerator` (4 and 1 for a 4-for-1 split); `time` its date (ms, 00:00 UTC). */\nexport interface SplitEvent {\n time: number;\n numerator: number;\n denominator: number;\n}\n\n/**\n * An earnings release: `time` when it was published (ms; a release after the close is after the session's close). The\n * values per share are adjusted for later splits, as PineScript gives them. A value the host does not have is left\n * out; a script that asks for it then stops with an error.\n */\nexport interface EarningsEvent {\n time: number;\n /** Reported earnings per share (`earnings.actual`), the analysts' estimate (`earnings.estimate`), standardized\n * earnings per share (`earnings.standardized`) */\n actual?: number | null;\n estimate?: number | null;\n standardized?: number | null;\n /** Estimated revenue (`earnings.future_revenue`) and the end of the fiscal period (ms) */\n revenueEstimate?: number | null;\n periodEnd?: number | null;\n}\n\n/** Events of a symbol, oldest first. */\nexport interface SymbolEvents {\n dividends?: DividendEvent[];\n splits?: SplitEvent[];\n earnings?: EarningsEvent[];\n /**\n * The lists hold the announced events still to come (`dividends.future_*`, `earnings.future_*` read them): without\n * it the future values are not known and reading them throws.\n */\n future?: { dividends?: boolean; earnings?: boolean };\n}\n\n/**\n * A request of `request.security` for another symbol whose bars the host has not given, or (`events`) of\n * `request.dividends` / `request.splits` / `request.earnings` for a symbol whose events it has not given.\n */\nexport interface SymbolDataRequest {\n symbol: string;\n timeframe: string;\n events?: boolean;\n}\n\n/**\n * Thrown by `executeScript` when `request.security` asked for bars of another symbol that `ChartContext.bars` did not\n * give (#179). `requests` lists them all, once each: load them, then run the script again.\n */\nexport class MissingSymbolDataError extends Error {\n constructor(readonly requests: SymbolDataRequest[]) {\n const bars = requests.filter((r) => !r.events);\n const events = requests.filter((r) => r.events);\n super(\n [\n bars.length ? `request.security needs the bars of ${bars.map((r) => `${r.symbol} (${r.timeframe})`).join(', ')}: pass them with ChartContext.bars.` : '',\n events.length ? `The script needs the events of ${events.map((r) => r.symbol).join(', ')}: pass them with ChartContext.events.` : '',\n ].filter(Boolean).join(' ')\n );\n this.name = 'MissingSymbolDataError';\n }\n}\n\n/** Requests of other symbols without bars in the current run. */\nlet missingSymbols: SymbolDataRequest[] = [];\n\nlet chartCtx: ChartContext = {};\n\nfunction chartTimeframe(): timeframeCore.TimeframeInfo {\n collector();\n if (!chartCtx.timeframe) {\n throw new Error('The chart timeframe is not known: pass it as executeScript(body, bars, inputs, { timeframe }).');\n }\n return timeframeCore.info(chartCtx.timeframe);\n}\n\nfunction exchangeTimezone(): string {\n collector();\n if (!chartCtx.timezone) {\n throw new Error('The exchange time zone is not known: pass it as executeScript(body, bars, inputs, { timezone }).');\n }\n return chartCtx.timezone;\n}\n\n/**\n * PineScript `timeframe.*`: the chart timeframe variables (from the chart context), and\n * `in_seconds(timeframe?)`, `from_seconds(seconds)`.\n */\nexport const timeframe: TimeframeNamespace = {\n ...timeframeCore,\n get period(): string {\n return chartTimeframe().period;\n },\n get main_period(): string {\n const main = chartCtx.mainTimeframe;\n return main ? timeframeCore.info(main).period : chartTimeframe().period;\n },\n get multiplier(): number {\n return chartTimeframe().multiplier;\n },\n get isintraday(): boolean {\n return chartTimeframe().isintraday;\n },\n get isdaily(): boolean {\n return chartTimeframe().isdaily;\n },\n get isweekly(): boolean {\n return chartTimeframe().isweekly;\n },\n get ismonthly(): boolean {\n return chartTimeframe().ismonthly;\n },\n get isminutes(): boolean {\n return chartTimeframe().isminutes;\n },\n get isseconds(): boolean {\n return chartTimeframe().isseconds;\n },\n get isticks(): boolean {\n return chartTimeframe().isticks;\n },\n get isdwm(): boolean {\n return chartTimeframe().isdwm;\n },\n /** PineScript `timeframe.change(tf)`: 1 on bars that open a new `tf` period (0 on the first bar). */\n change(tf: string): Series {\n return changeOf(tf || chartTimeframe().period);\n },\n /** Seconds in `timeframe`; without it (or with \"\") the chart timeframe, as in PineScript. */\n in_seconds(tf?: string): number {\n return timeframeCore.in_seconds(tf === undefined || tf === '' ? chartTimeframe().period : tf);\n },\n};\n\n/** A symbol property that the host passes in the chart context. */\nfunction symbolProperty(key: 'mintick' | 'pointvalue' | 'mincontract'): number {\n collector();\n const value = chartCtx[key];\n if (value === undefined) {\n if (key === 'mintick' && chartCtx.minmove !== undefined && chartCtx.pricescale !== undefined) {\n return chartCtx.minmove / chartCtx.pricescale;\n }\n throw new Error(`syminfo.${key} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);\n }\n return value;\n}\n\n/** A text value of the chart or the symbol that the host passes in the chart context; null (none) is \"\". */\nfunction chartText(\n key:\n | 'symbolType'\n | 'currency'\n | 'basecurrency'\n | 'root'\n | 'description'\n | 'foregroundColor'\n | 'backgroundColor'\n | 'prefix'\n | 'country'\n | 'currentContract'\n | 'sector'\n | 'industry'\n | 'isin'\n | 'volumetype',\n name: string\n): string {\n collector();\n const value = chartCtx[key];\n if (value === undefined) {\n throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);\n }\n // PineScript's na text is \"\" (`na(\"\")` is true)\n return value ?? '';\n}\n\n/** A number of the symbol that the host passes in the chart context; null (none) is na. */\nfunction symbolNumber(\n key: 'expirationDate' | 'employees' | 'shareholders' | 'sharesOutstandingTotal' | 'sharesOutstandingFloat',\n name: string\n): number {\n collector();\n const value = chartCtx[key];\n if (value === undefined) {\n throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);\n }\n return value ?? NaN;\n}\n\n/** A value of the analysts' figures of the symbol (`recommendations`, `targetPrice`); null (none) is na. */\nfunction analystNumber<K extends 'recommendations' | 'targetPrice'>(\n key: K,\n field: keyof NonNullable<ChartContext[K]>,\n name: string\n): number {\n collector();\n const group = chartCtx[key];\n if (group === undefined) {\n throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);\n }\n return group === null ? NaN : ((group as unknown as Record<string, number>)[field as string] ?? NaN);\n}\n\n/** The ticker id of the chart (or of the symbol of `request.security`); throws when not known. */\nfunction chartTickerid(): string {\n collector();\n if (!chartCtx.tickerid) {\n throw new Error('The chart symbol is not known: pass it as executeScript(body, bars, inputs, { tickerid }).');\n }\n return chartCtx.tickerid;\n}\n\n/** A ticker id cut at its prefix: [\"NASDAQ\", \"AAPL\"], [\"\", \"AAPL\"] without one. */\nfunction splitTickerid(tickerid: string): [string, string] {\n const at = tickerid.indexOf(':');\n return at < 0 ? ['', tickerid] : [tickerid.slice(0, at), tickerid.slice(at + 1)];\n}\n\n/** Month codes of futures contracts (F = January ... Z = December). */\nconst CONTRACT_SUFFIX = /^(.+?)[FGHJKMNQUVXZ](\\d{4}|\\d{2})$/;\n\n/** Root of a ticker: without the \"1!\" of a continuous future, or the month code and year of a future's contract. */\nfunction tickerRoot(ticker: string, symbolType: string | undefined): string {\n const continuous = /^(.+?)\\d+!$/.exec(ticker);\n if (continuous) return continuous[1]!;\n const contract = symbolType === 'futures' ? CONTRACT_SUFFIX.exec(ticker) : null;\n return contract ? contract[1]! : ticker;\n}\n\n/** A visible range value: the chart context's, else the time of bar `index` (NaN without bars). */\nfunction visibleBarTime(value: number | undefined, index: number): number {\n collector().usesVisibleRange = true;\n if (value !== undefined) return value;\n const bar = ctxBars.bars[index];\n return bar ? barTime(bar) : NaN;\n}\n\nfunction chartTypeIs(type: ChartType): boolean {\n collector();\n return (chartCtx.chartType ?? 'standard') === type;\n}\n\n/** `[minmove, pricescale]` of the chart symbol: from the chart context, else from its mintick. */\nfunction symbolScale(): [number, number] {\n collector();\n const { minmove, pricescale } = chartCtx;\n if (minmove !== undefined && pricescale !== undefined) return [minmove, pricescale];\n const [move, scale] = tickScale(symbolProperty('mintick'), pricescale);\n return [minmove ?? move, scale];\n}\n\n/**\n * PineScript `syminfo.*`, from the chart context (inside `request.security`, the requested symbol's). A field the\n * symbol has none of is na (\"\" for a text); a field the host did not give throws.\n */\nexport const syminfo: SyminfoNamespace = {\n get mintick(): number {\n return symbolProperty('mintick');\n },\n get minmove(): number {\n return symbolScale()[0];\n },\n get pricescale(): number {\n return symbolScale()[1];\n },\n get pointvalue(): number {\n return symbolProperty('pointvalue');\n },\n get mincontract(): number {\n return symbolProperty('mincontract');\n },\n get timezone(): string {\n return exchangeTimezone();\n },\n get tickerid(): string {\n return chartTickerid();\n },\n get main_tickerid(): string {\n const id = chartTickerid();\n return chartCtx.mainTickerid ?? id;\n },\n get ticker(): string {\n const id = chartTickerid();\n return chartCtx.ticker ?? splitTickerid(id)[1];\n },\n get prefix(): string {\n const id = chartTickerid();\n return chartCtx.prefix === undefined ? splitTickerid(id)[0] : (chartCtx.prefix ?? '');\n },\n get session(): string {\n collector();\n return chartCtx.sessionType ?? 'regular';\n },\n get type(): string {\n return chartText('symbolType', 'syminfo.type');\n },\n get currency(): string {\n return chartText('currency', 'syminfo.currency');\n },\n get basecurrency(): string {\n return chartText('basecurrency', 'syminfo.basecurrency');\n },\n get root(): string {\n if (chartCtx.root !== undefined) return chartText('root', 'syminfo.root');\n return tickerRoot(syminfo.ticker, chartCtx.symbolType);\n },\n get description(): string {\n return chartText('description', 'syminfo.description');\n },\n get country(): string {\n return chartText('country', 'syminfo.country');\n },\n get current_contract(): string {\n return chartText('currentContract', 'syminfo.current_contract');\n },\n get expiration_date(): number {\n return symbolNumber('expirationDate', 'syminfo.expiration_date');\n },\n get sector(): string {\n return chartText('sector', 'syminfo.sector');\n },\n get industry(): string {\n return chartText('industry', 'syminfo.industry');\n },\n get isin(): string {\n return chartText('isin', 'syminfo.isin');\n },\n get volumetype(): string {\n return chartText('volumetype', 'syminfo.volumetype');\n },\n get employees(): number {\n return symbolNumber('employees', 'syminfo.employees');\n },\n get shareholders(): number {\n return symbolNumber('shareholders', 'syminfo.shareholders');\n },\n get shares_outstanding_total(): number {\n return symbolNumber('sharesOutstandingTotal', 'syminfo.shares_outstanding_total');\n },\n get shares_outstanding_float(): number {\n return symbolNumber('sharesOutstandingFloat', 'syminfo.shares_outstanding_float');\n },\n get recommendations_buy(): number {\n return analystNumber('recommendations', 'buy', 'syminfo.recommendations_buy');\n },\n get recommendations_buy_strong(): number {\n return analystNumber('recommendations', 'buy_strong', 'syminfo.recommendations_buy_strong');\n },\n get recommendations_hold(): number {\n return analystNumber('recommendations', 'hold', 'syminfo.recommendations_hold');\n },\n get recommendations_sell(): number {\n return analystNumber('recommendations', 'sell', 'syminfo.recommendations_sell');\n },\n get recommendations_sell_strong(): number {\n return analystNumber('recommendations', 'sell_strong', 'syminfo.recommendations_sell_strong');\n },\n get recommendations_total(): number {\n return analystNumber('recommendations', 'total', 'syminfo.recommendations_total');\n },\n get recommendations_date(): number {\n return analystNumber('recommendations', 'date', 'syminfo.recommendations_date');\n },\n get target_price_average(): number {\n return analystNumber('targetPrice', 'average', 'syminfo.target_price_average');\n },\n get target_price_high(): number {\n return analystNumber('targetPrice', 'high', 'syminfo.target_price_high');\n },\n get target_price_low(): number {\n return analystNumber('targetPrice', 'low', 'syminfo.target_price_low');\n },\n get target_price_median(): number {\n return analystNumber('targetPrice', 'median', 'syminfo.target_price_median');\n },\n get target_price_estimates(): number {\n return analystNumber('targetPrice', 'estimates', 'syminfo.target_price_estimates');\n },\n get target_price_date(): number {\n return analystNumber('targetPrice', 'date', 'syminfo.target_price_date');\n },\n};\n\n/** A calendar function: `(time, timezone?)` on a UNIX time or on a Series of times. */\ninterface CalendarFunction {\n /**\n * @param time - A time in UNIX milliseconds.\n * @param timezone - Time zone to read the time in: \"America/New_York\", \"UTC+2\"... Default: the exchange's.\n * @returns The calendar field of that time.\n */\n (time: number, timezone?: string): number;\n /**\n * @param time - A Series of times in UNIX milliseconds, e.g. `time`.\n * @param timezone - Time zone to read the times in: \"America/New_York\", \"UTC+2\"... Default: the exchange's.\n * @returns Series of the calendar field of each time.\n */\n (time: Series, timezone?: string): Series;\n}\n\nfunction calendar(fn: (time: number, timezone: string) => number): CalendarFunction {\n return ((time: number | Series, timezone?: string) => {\n const tz = timezone ?? exchangeTimezone();\n return time instanceof Series ? Series.fromArray(ctxBars, time.toArray().map((t) => fn(t, tz))) : fn(time, tz);\n }) as CalendarFunction;\n}\n\n/**\n * The year of a time (2025...). Works on one time or on a Series of times (`year(time)` gives the value of each bar).\n * @example\n * ```js\n * const newYear = year(time).neq(year(time).offset(1));\n * bgcolor(color.when(newYear, color.new(color.blue, 80)));\n * ```\n */\nexport const year: CalendarFunction = calendar(timeCore.year);\n/**\n * The month of a time, 1 (January) to 12. Works on one time or on a Series of times (`month(time)` gives the value of each bar).\n * @example\n * ```js\n * const january = month(time).eq(1);\n * bgcolor(color.when(january, color.new(color.teal, 85)));\n * ```\n */\nexport const month: CalendarFunction = calendar(timeCore.month);\n/**\n * The week of the year of a time, 1 to 53. Works on one time or on a Series of times (`weekofyear(time)` gives the value of each bar).\n * @example\n * ```js\n * plot(weekofyear(time), \"Week\");\n * ```\n */\nexport const weekofyear: CalendarFunction = calendar(timeCore.weekofyear);\n/**\n * The day of the month of a time, 1 to 31. Works on one time or on a Series of times (`dayofmonth(time)` gives the value of each bar).\n * @example\n * ```js\n * plot(dayofmonth(time, \"UTC\"), \"Day of month\");\n * ```\n */\nexport const dayofmonth: CalendarFunction = calendar(timeCore.dayofmonth);\n/**\n * The day of the week of a time, 1 (Sunday) to 7 (Saturday), on one time or a Series of times; compare it with the\n * `dayofweek.monday`... constants.\n * @example\n * ```js\n * const monday = dayofweek(time).eq(dayofweek.monday);\n * bgcolor(color.when(monday, color.new(color.gray, 90)));\n * ```\n */\nexport const dayofweek: CalendarFunction & typeof pineConstants.daysOfWeek = Object.assign(calendar(timeCore.dayofweek), pineConstants.daysOfWeek);\n/**\n * The hour of a time, 0 to 23. Works on one time or on a Series of times (`hour(time)` gives the value of each bar).\n * @example\n * ```js\n * const morning = hour(time).lt(12);\n * bgcolor(color.when(morning, color.new(color.orange, 90)));\n * ```\n */\nexport const hour: CalendarFunction = calendar(timeCore.hour);\n/**\n * The minute of a time, 0 to 59. Works on one time or on a Series of times (`minute(time)` gives the value of each bar).\n * @example\n * ```js\n * plot(minute(time), \"Minute\");\n * ```\n */\nexport const minute: CalendarFunction = calendar(timeCore.minute);\n/**\n * The second of a time, 0 to 59. Works on one time or on a Series of times (`second(time)` gives the value of each bar).\n * @example\n * ```js\n * plot(second(time), \"Second\");\n * ```\n */\nexport const second: CalendarFunction = calendar(timeCore.second);\n\n/**\n * The UNIX time (milliseconds) of a date written as text.\n * @param dateString - A date such as \"2024-03-15\", \"2024-03-15T09:30\" or \"15 Mar 2024 09:30 GMT+1\"; without a time\n * zone it is UTC.\n * @returns The time in UNIX milliseconds.\n * @example\n * ```js\n * const start = timestamp(\"2024-01-01\");\n * bgcolor(color.when(time.gte(start), color.new(color.green, 92)));\n * ```\n */\nexport function timestamp(dateString: string): number;\n/**\n * The UNIX time (milliseconds) of a date and time in a time zone.\n * @param timezone - Time zone: \"America/New_York\", \"UTC+2\"...\n * @param year - Year, e.g. 2024.\n * @param month - Month, 1 to 12.\n * @param day - Day of the month, 1 to 31.\n * @param hour - Hour, 0 to 23. Default: 0.\n * @param minute - Minute. Default: 0.\n * @param second - Second. Default: 0.\n * @returns The time in UNIX milliseconds.\n * @example\n * ```js\n * const open = timestamp(\"America/New_York\", 2024, 3, 15, 9, 30);\n * ```\n */\nexport function timestamp(\n timezone: string,\n year: number,\n month: number,\n day: number,\n hour?: number,\n minute?: number,\n second?: number\n): number;\n/**\n * The UNIX time (milliseconds) of a date and time in the exchange's time zone.\n * @param year - Year, e.g. 2024.\n * @param month - Month, 1 to 12.\n * @param day - Day of the month, 1 to 31.\n * @param hour - Hour, 0 to 23. Default: 0.\n * @param minute - Minute. Default: 0.\n * @param second - Second. Default: 0.\n * @returns The time in UNIX milliseconds.\n * @example\n * ```js\n * const from = timestamp(2024, 1, 1);\n * plotshape(time.eq(from), \"Start\");\n * ```\n */\nexport function timestamp(year: number, month: number, day: number, hour?: number, minute?: number, second?: number): number;\nexport function timestamp(first: string | number, ...rest: Array<number | undefined>): number {\n if (typeof first === 'number') {\n const [m, d, h, mi, s] = rest as [number, number, number?, number?, number?];\n return timeCore.timestamp(exchangeTimezone(), first, m, d, h, mi, s);\n }\n if (rest.length === 0) return timeCore.timestamp(first);\n const [y, m, d, h, mi, s] = rest as [number, number, number, number?, number?, number?];\n return timeCore.timestamp(first, y, m, d, h, mi, s);\n}\n\n/**\n * Whether a time is inside a session (trading hours).\n * @param time - A time in UNIX milliseconds, e.g. `c.time` in `eachBar()`.\n * @param session - Session hours and days: \"0930-1600\", \"0930-1600:23456\" (Monday to Friday), \"1800-0500\" (overnight).\n * @param timezone - Time zone of the session hours. Default: the exchange's.\n * @returns true when the time is in the session.\n * @example\n * ```js\n * const regular = eachBar((c) => inSession(c.time, \"0930-1600\"));\n * bgcolor(color.when(regular, color.new(color.blue, 92)));\n * ```\n */\nexport function inSession(time: number, session: string, timezone?: string): boolean {\n return timeCore.inSession(time, session, timezone ?? exchangeTimezone());\n}\n\n/**\n * Text functions: `str.tostring` (a number as text), `str.format` (a pattern with values), `str.format_time` (a date),\n * search, replace, split, case... `str.format_time` and the dates of `str.format` use the exchange's time zone by\n * default.\n * @example\n * ```js\n * eachBar((c) => {\n * if (barstate.islast) log.info(str.format(\"Close {0} at {1}\", c.get(close), str.format_time(c.get(time), \"HH:mm\")));\n * });\n * ```\n */\nexport const str: typeof strCore = strictNamespace('str', {\n ...strCore,\n // format.mintick uses the chart symbol's tick and price scale (syminfo.mintick, syminfo.pricescale)\n tostring: ((value: unknown, format?: string, mintick?: number, pricescale?: number) =>\n format === 'mintick' && mintick === undefined\n ? strCore.tostring(value as never, format, syminfo.mintick, pricescale ?? syminfo.pricescale)\n : strCore.tostring(value as never, format, mintick, pricescale)) as typeof strCore.tostring,\n // the exchange time zone by default; the documentation is the library function's\n format_time: ((time: number, format: string = \"yyyy-MM-dd'T'HH:mm:ssZ\", timezone?: string): string =>\n strCore.format_time(time, format, timezone ?? exchangeTimezone())) as typeof strCore.format_time,\n format: ((pattern: string, ...args: unknown[]): string => formatMessage(pattern, args, exchangeTimezone)) as typeof strCore.format,\n});\n\n// \u2500\u2500 Session values (issue #100) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Bar time in ms (PineScript `time`). */\nfunction barTime(bar: Bar): number {\n return (bar.time as number) * (chartCtx.timeUnit === 'ms' ? 1 : 1000);\n}\n\nconst toSpec = (s: SessionSpec | string): SessionSpec => (typeof s === 'string' ? { session: s } : s);\n\nlet sessionCache: { ctx: ChartContext; bars: SessionBars; regular: SessionBars } | null = null;\n\n/** Session calendars of the run (loaded bars and regular hours), built from the chart context. */\nfunction sessionBars(): { bars: SessionBars; regular: SessionBars } {\n const tz = exchangeTimezone();\n const tf = chartTimeframe().period;\n if (!chartCtx.session) {\n throw new Error('The session is not known: pass it as executeScript(body, bars, inputs, { session }).');\n }\n if (sessionCache?.ctx !== chartCtx) {\n const loaded = toSpec(chartCtx.session);\n const regular = chartCtx.regularSession ? toSpec(chartCtx.regularSession) : loaded;\n sessionCache = {\n ctx: chartCtx,\n bars: new SessionBars(new TradingCalendar(tz, loaded), tf),\n regular: new SessionBars(new TradingCalendar(tz, { holidays: loaded.holidays, ...regular }), tf),\n };\n }\n return sessionCache;\n}\n\nfunction perBar(fn: (t: number, i: number, times: number[]) => number): Series {\n const times = ctxBars.bars.map(barTime);\n return Series.fromArray(ctxBars, times.map((t, i) => fn(t, i, times)));\n}\n\n/** A Series that can also be called, like PineScript's `time` (variable) and `time(...)` (function). */\nfunction callableSeries<F extends (...args: never[]) => Series>(series: Series, fn: F): Series & F {\n Object.setPrototypeOf(fn, Series.prototype);\n Object.assign(fn, series);\n return fn as Series & F;\n}\n\n/** `time(tf, session, timezone)` / `time_close(...)` periods of the run's chart (see session/context `sessionPeriods`). */\nfunction chartSessionPeriods(timeframeString: string, session?: string, timezone?: string): SessionPeriods {\n const { bars } = sessionBars();\n return sessionPeriods(bars, { ...chartCtx, timezone: exchangeTimezone() }, timeframeString, session, timezone);\n}\n\n/**\n * The open time of the period of `tf` that holds each bar, in UNIX milliseconds; na on bars outside `session`.\n * @param tf - Timeframe of the periods: \"D\", \"W\", \"60\"... Default: the chart's.\n * @param session - Session hours, e.g. \"0930-1600\"; bars outside it give na. Default: the symbol's.\n * @param timezone - Time zone of the session hours. Default: the exchange's.\n * @returns Series of period open times.\n */\nfunction timeFunction(tf?: string, session?: string, timezone?: string): Series {\n collector();\n const { open } = chartSessionPeriods(tf || chartTimeframe().period, session, timezone);\n return perBar((t) => open(t));\n}\n\n/**\n * The close time of the period of `tf` that holds each bar, in UNIX milliseconds; na on bars outside `session`.\n * @param tf - Timeframe of the periods: \"D\", \"W\", \"60\"... Default: the chart's.\n * @param session - Session hours, e.g. \"0930-1600\"; bars outside it give na. Default: the symbol's.\n * @param timezone - Time zone of the session hours. Default: the exchange's.\n * @returns Series of period close times.\n */\nfunction timeCloseFunction(tf?: string, session?: string, timezone?: string): Series {\n collector();\n const { close } = chartSessionPeriods(tf || chartTimeframe().period, session, timezone);\n return perBar((t) => close(t));\n}\n\n/** Current time of the run in ms, see `ChartContext.now`. */\nlet runNow = NaN;\n\n/** PineScript `timenow`: the current time in ms, the same on every bar of a run (`ChartContext.now`). */\nexport const timenow = new Series(ctxBars, () => {\n incremental.nonIncremental('timenow');\n return runNow;\n});\n\n/**\n * The open time of each bar, in UNIX milliseconds (a Series). Called as `time(tf?, session?, timezone?)`: the open\n * time of the `tf` period that holds the bar, na outside `session`.\n * @example\n * ```js\n * const newDay = time(\"D\").neq(time(\"D\").offset(1));\n * bgcolor(color.when(newDay, color.new(color.gray, 85)));\n * ```\n */\nexport const time = callableSeries(new Series(ctxBars, (b) => barTime(b)), timeFunction);\n\n/**\n * The close time of each bar, in UNIX milliseconds (a Series). Called as `time_close(tf?, session?, timezone?)`: the\n * close time of the `tf` period that holds the bar, na outside `session`.\n * @example\n * ```js\n * plot(time_close.sub(time).div(60000), \"Bar minutes\");\n * ```\n */\nexport const time_close = callableSeries(\n new Series(ctxBars, (_b, i) => sessionBars().bars.closeOf(barTime(ctxBars.bars[i]!), chartTimeframe().period)),\n timeCloseFunction\n);\n\n/** PineScript `time_tradingday`: 00:00 UTC of the trading day of each bar, in ms. */\nexport const time_tradingday = new Series(ctxBars, (b) => sessionBars().bars.tradingDayTime(barTime(b)));\n\nfunction changeOf(tf: string, firstBar = false): Series {\n const { bars } = sessionBars();\n // a bar without a period (after an early close) is no change, and neither is the bar after it\n const changed = (a: number, b: number): boolean => !Number.isNaN(a) && !Number.isNaN(b) && a !== b;\n return perBar((t, i, times) => ((i > 0 ? changed(bars.timeOf(t, tf), bars.timeOf(times[i - 1]!, tf)) : firstBar) ? 1 : 0));\n}\n\n/**\n * Default anchor of `ta.vwap` (#173, #178): the first bar and each bar whose trading day differs from the last bar\n * that has one. Bars after an early close have no day: the first of them continues the day before it, each further\n * one starts a new sum, and the next day starts on its first bar (where `timeframe.change(\"D\")` is false). On\n * D / W / M charts every bar.\n */\nfunction vwapAnchor(): Series {\n if (chartTimeframe().isdwm) return barFlag(() => true);\n const { bars } = sessionBars();\n let last = NaN;\n let previous = NaN;\n return perBar((t, i) => {\n const day = bars.timeOf(t, '1D');\n const isNew = i === 0 || (Number.isNaN(day) ? Number.isNaN(previous) : day !== last);\n if (!Number.isNaN(day)) last = day;\n previous = day;\n return isNew ? 1 : 0;\n });\n}\n\nfunction flag(key: keyof SessionFlags): Series {\n const { bars, regular } = sessionBars();\n const values = sessionFlags(ctxBars.bars.map(barTime), bars, regular)[key];\n return Series.fromArray(ctxBars, values.map((v) => (v ? 1 : 0)));\n}\n\n/** A 1 / 0 Series from a per-bar test on the bar index and the number of bars. */\nfunction barFlag(test: (i: number, n: number) => boolean): Series {\n const n = ctxBars.bars.length;\n return Series.fromArray(ctxBars, Array.from({ length: n }, (_, i) => (test(i, n) ? 1 : 0)));\n}\n\n/**\n * An intrabar run reads the flag on the same bars as the run before, with at most one bar more, and the flags only\n * differ on their last bars: the values are kept between runs (the series only reads them).\n */\nconst FLAG_TAIL = 3;\nconst flagValues = new Map<string, number[]>();\nfunction namedFlag(name: string, test: (i: number, n: number) => boolean): Series {\n if (!intrabarRun) return barFlag(test);\n const n = ctxBars.bars.length;\n let values = flagValues.get(name);\n if (!values || values.length > n) {\n values = Array.from({ length: n }, (_, i) => (test(i, n) ? 1 : 0));\n flagValues.set(name, values);\n } else {\n const from = Math.max(0, Math.min(values.length, n) - FLAG_TAIL);\n values.length = n;\n for (let i = from; i < n; i++) values[i] = test(i, n) ? 1 : 0;\n }\n return Series.fromArray(ctxBars, values);\n}\n\n/** Number of bars of the chart: an intrabar run ends before the chart's last bar. */\nconst chartBarCount = (n: number): number => (intrabarRun ? intrabarRun.lastBarIndex + 1 : n);\n\nconst lastRealtime = (i: number, n: number): boolean => i === n - 1 && chartCtx.realtime === true;\n\n/**\n * PineScript `barstate.*` (1 / 0 per bar). All bars but the last are confirmed history bars. The last bar is\n * confirmed only when the host says so (`ChartContext.lastBarConfirmed`, e.g. the closing update of a realtime\n * bar), and is a realtime bar only when it receives live updates (`ChartContext.realtime`); without live updates\n * it is a history bar, as in PineScript.\n * `islastconfirmedhistory` is the last bar when it is confirmed and not realtime, else the bar before it.\n */\nexport const barstate: BarstateNamespace = {\n get isfirst(): Series { return namedFlag('isfirst', (i) => i === 0); },\n get islast(): Series { return namedFlag('islast', (i, n) => i === chartBarCount(n) - 1); },\n get isconfirmed(): Series { return namedFlag('isconfirmed', (i, n) => i < n - 1 || chartCtx.lastBarConfirmed === true); },\n get isrealtime(): Series { return namedFlag('isrealtime', lastRealtime); },\n get ishistory(): Series { return namedFlag('ishistory', (i, n) => !lastRealtime(i, n)); },\n get isnew(): Series { return namedFlag('isnew', (i, n) => !lastRealtime(i, n) || chartCtx.lastBarNew !== false); },\n get islastconfirmedhistory(): Series {\n return namedFlag('islastconfirmedhistory', (i, n) => {\n // moves to the next bar with each new bar: not kept by an incremental run (#196), but the same in the intrabar\n // runs of a backtest (#206)\n if (!intrabarRun) incremental.nonIncremental('barstate.islastconfirmedhistory');\n const lastConfirmed = chartCtx.lastBarConfirmed === true && chartCtx.realtime !== true;\n const count = chartBarCount(n);\n return i === (lastConfirmed ? count - 1 : count - 2);\n });\n },\n};\n\n/**\n * PineScript `session.*` (1 / 0 per bar) and the constants `session.regular` / `session.extended`.\n * First and last bars are per session period; market / pre / post market use the regular hours.\n */\nexport const session: SessionNamespace = {\n regular: 'regular',\n extended: 'extended',\n get isfirstbar(): Series { return flag('isfirstbar'); },\n get islastbar(): Series { return flag('islastbar'); },\n get ismarket(): Series { return flag('ismarket'); },\n get ispremarket(): Series { return flag('ispremarket'); },\n get ispostmarket(): Series { return flag('ispostmarket'); },\n get isfirstbar_regular(): Series { return flag('isfirstbar_regular'); },\n get islastbar_regular(): Series { return flag('islastbar_regular'); },\n};\n\n// \u2500\u2500 request.security (issue #101) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** PineScript `barmerge.*` constants of `request.security`. */\nexport const barmerge: BarmergeNamespace = {\n gaps_on: 'gaps_on',\n gaps_off: 'gaps_off',\n lookahead_on: 'lookahead_on',\n lookahead_off: 'lookahead_off',\n} as const;\n\nconst HEIKIN_ASHI = 'heikinashi:';\n\n/** PineScript `ticker.heikinashi(symbol)` / `ticker.standard(symbol)` for the chart symbol. */\nexport const ticker: TickerNamespace = {\n heikinashi(symbol: string): string {\n return HEIKIN_ASHI + symbol;\n },\n standard(symbol: string): string {\n return symbol.startsWith(HEIKIN_ASHI) ? symbol.slice(HEIKIN_ASHI.length) : symbol;\n },\n};\n\n/** What an expression of `request.security` may return. */\nexport type SecurityValue = Series | number | boolean | Array<Series | number | boolean>;\n\nfunction valuesOf(value: Series | number | boolean, length: number): number[] {\n if (!(value instanceof Series)) return new Array<number>(length).fill(Number(value));\n if (value.bars !== ctxBars.bars) {\n throw new Error(\n 'request.security(): the expression returned a series computed on the chart bars. ' +\n 'Compute the series inside the expression, e.g. () => ta.ema(close, 10).'\n );\n }\n return value.toArray().slice();\n}\n\n/**\n * PineScript `request.security` on a timeframe equal to or higher than the chart's. For the chart symbol\n * (`syminfo.tickerid`, `\"\"`, `ticker.heikinashi(...)`, `ticker.standard(...)`) the higher-timeframe bars are built by\n * grouping the chart bars; another symbol's bars come from `ChartContext.bars` (#179) and are merged on the chart bars\n * by close time (lookahead off) or by open time / trading day (lookahead on), see `securityOther`. `expression` runs\n * on those bars (its `ta.*` calls, tuples, `timeframe.*` and `syminfo.*` see them). A lower timeframe throws.\n *\n * A symbol that does not exist (bars []) stops the script with \"Invalid symbol: X\", or gives na with\n * `ignore_invalid_symbol`.\n *\n * PineScript rules: lookahead off shows a period's value from the\n * bar that completes it; lookahead on from its first bar; gaps on keeps only the bar where the value appears.\n * Built bars can differ from the exchange's bars (official open / close, volume).\n */\nfunction security<T extends SecurityValue>(\n symbol: string,\n timeframe: string,\n expression: () => T,\n gaps: string = barmerge.gaps_off,\n lookahead: string = barmerge.lookahead_off,\n ignore_invalid_symbol: boolean = false\n): T extends unknown[] ? Series[] : Series {\n collector();\n // other bars merged on the chart bars: not resumed by an incremental run (#196)\n incremental.nonIncremental('request.security');\n const heikin = symbol.startsWith(HEIKIN_ASHI);\n const base = heikin ? symbol.slice(HEIKIN_ASHI.length) : symbol;\n const chart = chartTimeframe();\n const tf = timeframeCore.info(timeframe || chart.period).period;\n if (base !== '' && base !== chartCtx.tickerid) {\n return externalSecurity(base, heikin, tf, expression, gaps, lookahead, ignore_invalid_symbol, false);\n }\n const ticks = timeframeCore.info(tf).isticks && tf !== chart.period;\n if (ticks || timeframeCore.in_seconds(tf) < timeframeCore.in_seconds(chart.period)) {\n // a lower timeframe of the chart symbol, or its ticks: its bars come from ChartContext.bars (#181, #214)\n return externalSecurity(chartCtx.tickerid ?? '', heikin, tf, expression, gaps, lookahead, ignore_invalid_symbol, true);\n }\n\n const chartBars = ctxBars.bars;\n const times = chartBars.map(barTime);\n let htf: Bar[];\n let group: number[];\n let latest: number[];\n if (tf === chart.period) {\n htf = chartBars;\n group = chartBars.map((_, i) => i);\n latest = group;\n } else {\n const { bars: loaded, regular } = sessionBars();\n // D / W / M periods follow the regular hours; intraday periods the loaded session\n const calendar = timeframeCore.info(tf).isdwm ? regular : loaded;\n const starts = times.map((t) => calendar.timeOf(t, tf));\n const dayPeriods = times.map((t, i) => {\n const at = loaded.locateBar(t);\n const periods = at ? calendar.calendar.periods(at.date) : [];\n return periods.length ? calendar.timeOf(periods[0]![0], tf) : starts[i]!;\n });\n const tfInfo = timeframeCore.info(tf);\n strayPeriods(starts, dayPeriods, times, loaded, tfInfo.isdwm ? null : timeframeCore.in_seconds(tf) * 1000);\n const reaches = times.map((t) => loaded.closeOf(t, chart.period) >= calendar.periodEnd(t, tf));\n ({ group, latest } = periodsOf(starts, dayPeriods, reaches));\n const unit = chartCtx.timeUnit === 'ms' ? 1 : 1000;\n // a higher-timeframe bar ends at the bar that completes it (no value from after the completion)\n const after = afterCompletion(group, latest);\n const kept = (_: unknown, i: number): boolean => !after[i];\n htf = resample(chartBars.filter(kept), starts.map((s) => s / unit).filter(kept)).bars;\n }\n if (heikin) htf = heikinAshi(htf);\n\n const savedCtx = chartCtx;\n let result: T;\n let values: number[][];\n ctxBars.setAll(htf);\n chartCtx = { ...chartCtx, timeframe: tf, mainTimeframe: chartCtx.mainTimeframe ?? chartCtx.timeframe };\n try {\n result = expression();\n const parts = Array.isArray(result) ? result : [result];\n values = parts.map((p) => valuesOf(p, htf.length));\n } finally {\n ctxBars.setAll(chartBars);\n chartCtx = savedCtx;\n }\n const mapped = values.map((v) =>\n Series.fromArray(ctxBars, mapToChart(v, group, latest, lookahead === barmerge.lookahead_on, gaps === barmerge.gaps_on))\n );\n return (Array.isArray(result) ? mapped : mapped[0]) as T extends unknown[] ? Series[] : Series;\n}\n\n/** Bars of a symbol on a timeframe from `ChartContext.bars`, with its calendar and the values of `expression` on them. */\ninterface ExternalRun<T> {\n bars: Bar[];\n info: SymbolInfo;\n result: T;\n values: number[][];\n}\n\n/**\n * Runs `expression` on the bars of `symbol` / `tf` given by `ChartContext.bars` (#179, #181). Bars not given: the\n * request is recorded for the {@link MissingSymbolDataError} and the expression runs on no bar. `own`: the chart\n * symbol, whose calendar defaults to the chart's.\n */\nfunction runExternal<T extends SecurityValue>(\n symbol: string,\n heikin: boolean,\n tf: string,\n expression: () => T,\n ignoreInvalid: boolean,\n own: boolean\n): ExternalRun<T> {\n let bars = chartCtx.bars?.(symbol, tf);\n if (bars === undefined && !missingSymbols.some((r) => r.symbol === symbol && r.timeframe === tf)) {\n missingSymbols.push({ symbol, timeframe: tf });\n }\n if (bars !== undefined && bars.length === 0 && !ignoreInvalid) throw new Error(`Invalid symbol: ${symbol}`);\n bars ??= [];\n if (heikin) bars = heikinAshi(bars);\n const given = chartCtx.symbolInfo?.(symbol);\n const info: SymbolInfo = own ? { ...chartCtx, ...given } : (given ?? {});\n const chartBars = ctxBars.bars;\n const savedCtx = chartCtx;\n let result: T;\n let values: number[][];\n ctxBars.setAll(bars);\n // the expression sees that symbol: its ticker, timeframe, calendar and properties (the chart's own symbol stays the\n // main one)\n const seen: ChartContext = {\n ...chartCtx,\n tickerid: symbol,\n timeframe: tf,\n mainTickerid: chartCtx.mainTickerid ?? chartCtx.tickerid,\n mainTimeframe: chartCtx.mainTimeframe ?? chartCtx.timeframe,\n };\n for (const key of SYMBOL_INFO_KEYS) (seen as Record<string, unknown>)[key] = info[key];\n chartCtx = seen;\n try {\n result = expression();\n const parts = Array.isArray(result) ? result : [result];\n values = parts.map((p) => valuesOf(p, bars!.length));\n } finally {\n ctxBars.setAll(chartBars);\n chartCtx = savedCtx;\n }\n return { bars, info, result, values };\n}\n\n/** The chart for the merge functions of `security/other`. */\nfunction mergeChart(): OtherSymbolChart {\n return {\n timeframe: chartTimeframe().period,\n timezone: chartCtx.timezone,\n session: chartCtx.session,\n timeUnit: chartCtx.timeUnit,\n // the realtime rule applies to a last bar that receives live updates\n lastBarConfirmed: chartCtx.realtime !== true,\n };\n}\n\n/**\n * `request.security` of another symbol (#179), or of the chart symbol on a lower timeframe (#181): its bars from\n * `ChartContext.bars`, merged by `securityOther`.\n */\nfunction externalSecurity<T extends SecurityValue>(\n symbol: string,\n heikin: boolean,\n tf: string,\n expression: () => T,\n gaps: string,\n lookahead: string,\n ignoreInvalid: boolean,\n own: boolean\n): T extends unknown[] ? Series[] : Series {\n const { bars, info, result, values } = runExternal(symbol, heikin, tf, expression, ignoreInvalid, own);\n const index = securityOther(ctxBars.bars, bars, tf, mergeChart(), {\n gaps: gaps === barmerge.gaps_on,\n lookahead: lookahead === barmerge.lookahead_on,\n other: info,\n });\n const mapped = values.map((v) => Series.fromArray(ctxBars, index.map((j) => (j < 0 ? NaN : (v[j] ?? NaN)))));\n return (Array.isArray(result) ? mapped : mapped[0]) as T extends unknown[] ? Series[] : Series;\n}\n\n/**\n * PineScript `request.security_lower_tf(symbol, timeframe, expression, ignore_invalid_symbol)` (#181): for each\n * chart bar, the array of the values of `expression` on the bars of the lower timeframe that the chart bar contains\n * (those whose close is after the open of the chart bar and at or before its close; empty when there are none).\n * The bars come from `ChartContext.bars`, for the chart symbol (`\"\"`, `syminfo.tickerid`) as for another symbol.\n * Returns one array per chart bar (oldest first), or one such list per tuple part.\n * @throws Error when `timeframe` is higher than the chart timeframe\n */\nfunction security_lower_tf<T extends SecurityValue>(\n symbol: string,\n timeframe: string,\n expression: () => T,\n ignore_invalid_symbol: boolean = false\n): T extends unknown[] ? number[][][] : number[][] {\n collector();\n incremental.nonIncremental('request.security_lower_tf');\n const heikin = symbol.startsWith(HEIKIN_ASHI);\n const base = heikin ? symbol.slice(HEIKIN_ASHI.length) : symbol;\n const chart = chartTimeframe();\n const tf = timeframeCore.info(timeframe || chart.period).period;\n if (timeframeCore.in_seconds(tf) > timeframeCore.in_seconds(chart.period)) {\n throw new Error(`request.security_lower_tf: timeframe \"${tf}\" is higher than the chart timeframe \"${chart.period}\".`);\n }\n const own = base === '' || base === chartCtx.tickerid;\n const ticker = own ? (chartCtx.tickerid ?? '') : base;\n const { bars, info, result, values } = runExternal(ticker, heikin, tf, expression, ignore_invalid_symbol, own);\n const ranges = securityLowerTf(ctxBars.bars, bars, tf, mergeChart(), { other: info });\n const mapped = values.map((v) => ranges.map(([from, to]) => v.slice(from, to)));\n return (Array.isArray(result) ? mapped : mapped[0]) as T extends unknown[] ? number[][][] : number[][];\n}\n\n/**\n * PineScript `request.seed(source, symbol, expression, ignore_invalid_symbol)` (#205): `expression` on a seed data\n * series, on the chart timeframe. The series is the symbol `ChartContext.seedSymbol(source, symbol)` (default\n * `\"<SOURCE>:<SYMBOL>\"` upper-cased), read as `request.security(<that symbol>, \"\", expression)`.\n */\nfunction seed<T extends SecurityValue>(\n source: string,\n symbol: string,\n expression: () => T,\n ignore_invalid_symbol: boolean = false\n): T extends unknown[] ? Series[] : Series {\n const ticker = chartCtx.seedSymbol?.(source, symbol) ?? `${source.toUpperCase()}:${symbol.toUpperCase()}`;\n return security(ticker, '', expression, barmerge.gaps_off, barmerge.lookahead_off, ignore_invalid_symbol);\n}\n\n/** PineScript `request.*`: `security` (issue #101, other symbols #179, lower timeframes #181), `security_lower_tf` and `seed` (#205). */\n/** PineScript parameters of `request.security` / `request.security_lower_tf`, in their positional order. */\nconst SECURITY_PARAMETERS = ['symbol', 'timeframe', 'expression', 'gaps', 'lookahead', 'ignore_invalid_symbol', 'currency', 'calc_bars_count'] as const;\nconst SECURITY_LOWER_TF_PARAMETERS = ['symbol', 'timeframe', 'expression', 'ignore_invalid_symbol', 'currency', 'ignore_invalid_timeframe', 'calc_bars_count'] as const;\nconst SEED_PARAMETERS = ['source', 'symbol', 'expression', 'ignore_invalid_symbol', 'calc_bars_count'] as const;\n\n/** Named arguments of `request.security` (PineScript names). */\nexport interface SecurityArgs<T extends SecurityValue = SecurityValue> {\n symbol?: string;\n timeframe?: string;\n expression?: () => T;\n gaps?: string;\n lookahead?: string;\n ignore_invalid_symbol?: boolean;\n currency?: string;\n calc_bars_count?: number;\n}\n\n/** Named arguments of `request.security_lower_tf` (PineScript names). */\nexport interface SecurityLowerTfArgs<T extends SecurityValue = SecurityValue> {\n symbol?: string;\n timeframe?: string;\n expression?: () => T;\n ignore_invalid_symbol?: boolean;\n currency?: string;\n ignore_invalid_timeframe?: boolean;\n calc_bars_count?: number;\n}\n\n/** `currency` and `calc_bars_count` change the values in PineScript: they throw instead of being ignored. */\nfunction unsupportedSecurityArgs(name: string, currency: unknown, calcBarsCount: unknown): void {\n if (currency !== undefined && currency !== '' && currency !== 'NONE') {\n throw new Error(`${name}(): the currency argument (conversion of the values) is not supported.`);\n }\n if (calcBarsCount !== undefined) throw new Error(`${name}(): the calc_bars_count argument is not supported.`);\n}\n\n/** `request.security` with PineScript's named arguments: `request.security(sym, \"D\", () => close, { lookahead: barmerge.lookahead_on })`. */\nfunction securityCall<T extends SecurityValue>(\n ...args:\n | [symbol: string, timeframe: string, expression: () => T, gaps?: string, lookahead?: string, ignore_invalid_symbol?: boolean]\n | [symbol: string, timeframe: string, expression: () => T, args: SecurityArgs<T>]\n | [args: SecurityArgs<T> & { symbol: string; timeframe: string; expression: () => T }]\n): T extends unknown[] ? Series[] : Series {\n const a = namedArguments('request.security', SECURITY_PARAMETERS, args);\n unsupportedSecurityArgs('request.security', a[6], a[7]);\n return security(a[0] as string, a[1] as string, a[2] as () => T, a[3] as string | undefined, a[4] as string | undefined, a[5] as boolean | undefined);\n}\n\n/** `request.security_lower_tf` with PineScript's named arguments. */\nfunction securityLowerTfCall<T extends SecurityValue>(\n ...args:\n | [symbol: string, timeframe: string, expression: () => T, ignore_invalid_symbol?: boolean]\n | [symbol: string, timeframe: string, expression: () => T, args: SecurityLowerTfArgs<T>]\n | [args: SecurityLowerTfArgs<T> & { symbol: string; timeframe: string; expression: () => T }]\n): T extends unknown[] ? number[][][] : number[][] {\n const a = namedArguments('request.security_lower_tf', SECURITY_LOWER_TF_PARAMETERS, args);\n unsupportedSecurityArgs('request.security_lower_tf', a[4], a[6]);\n if (a[5] !== undefined && a[5] !== false) throw new Error('request.security_lower_tf(): the ignore_invalid_timeframe argument is not supported.');\n return security_lower_tf(a[0] as string, a[1] as string, a[2] as () => T, a[3] as boolean | undefined);\n}\n\n/** Named arguments of `request.seed` (PineScript names). */\nexport interface SeedArgs<T extends SecurityValue = SecurityValue> {\n source?: string;\n symbol?: string;\n expression?: () => T;\n ignore_invalid_symbol?: boolean;\n calc_bars_count?: number;\n}\n\n/** `request.seed` with PineScript's named arguments. */\nfunction seedCall<T extends SecurityValue>(\n ...args:\n | [source: string, symbol: string, expression: () => T, ignore_invalid_symbol?: boolean]\n | [source: string, symbol: string, expression: () => T, args: SeedArgs<T>]\n | [args: SeedArgs<T> & { source: string; symbol: string; expression: () => T }]\n): T extends unknown[] ? Series[] : Series {\n const a = namedArguments('request.seed', SEED_PARAMETERS, args);\n unsupportedSecurityArgs('request.seed', undefined, a[4]);\n return seed(a[0] as string, a[1] as string, a[2] as () => T, a[3] as boolean | undefined);\n}\n\n// \u2500\u2500 request.dividends / request.splits / request.earnings (#211) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The events of `ticker` (\"\" or the chart's: the chart symbol); {} while the host has not given them (the run ends with\n * a MissingSymbolDataError). */\nfunction symbolEvents(ticker: string): SymbolEvents {\n collector();\n const symbol = ticker === '' ? chartTickerid() : ticker;\n const events = chartCtx.events?.(symbol);\n if (events === undefined) {\n if (!missingSymbols.some((r) => r.events && r.symbol === symbol)) missingSymbols.push({ symbol, timeframe: '', events: true });\n return {};\n }\n return events;\n}\n\n/** One value of each event; throws when no event has it (the host does not have it), na where one has none. */\nfunction eventField<E extends object>(list: E[], field: keyof E, name: string, ticker: string): number[] {\n if (list.length && list.every((e) => e[field] === undefined)) {\n throw new Error(`${name}: the ${String(field)} values of ${ticker || 'the chart symbol'} are not known.`);\n }\n return list.map((e) => {\n const v = e[field] as unknown;\n return typeof v === 'number' ? v : NaN;\n });\n}\n\n/** A Series of event values on the chart bars, placed by PineScript's rules (see `security/events`). */\nfunction eventSeries(times: number[], values: number[], gaps: string | undefined, lookahead: string | undefined): Series {\n incremental.nonIncremental('request.dividends / splits / earnings');\n const opens = ctxBars.bars.map(barTime);\n const tf = chartTimeframe().period;\n const span = timeframeCore.info(tf).isticks ? 0 : timeframeCore.in_seconds(tf) * 1000;\n const { bars } = sessionBars();\n // a bar without a session period closes where the next one opens\n const closes = opens.map((t, i) => {\n const c = bars.closeOf(t, tf);\n return Number.isFinite(c) ? c : (opens[i + 1] ?? t + span);\n });\n const order = times.map((_, i) => i).sort((a, b) => times[a]! - times[b]!);\n const events = order.map((i) => ({ time: times[i]!, value: values[i]! }));\n return Series.fromArray(\n ctxBars,\n eventsOnBars(opens, closes, tf, events, { gaps: gaps === barmerge.gaps_on, lookahead: lookahead === barmerge.lookahead_on })\n );\n}\n\n/** PineScript `dividends.*`: the fields of `request.dividends` and the next announced dividend of the chart symbol. */\nexport const dividends: DividendsNamespace = {\n net: 'net',\n gross: 'gross',\n /** Amount of the next dividend (net), na when none is announced */\n get future_amount(): number {\n return nextDividend()?.net ?? NaN;\n },\n /** Ex-date of the next dividend (ms) */\n get future_ex_date(): number {\n return nextDividend()?.time ?? NaN;\n },\n /** Payment date of the next dividend (ms) */\n get future_pay_date(): number {\n return nextDividend()?.payDate ?? NaN;\n },\n} as const;\n\n/** PineScript `splits.*`: the fields of `request.splits`. */\nexport const splits: SplitsNamespace = { numerator: 'numerator', denominator: 'denominator' } as const;\n\n/** PineScript `earnings.*`: the fields of `request.earnings` and the next earnings release of the chart symbol. */\nexport const earnings: EarningsNamespace = {\n actual: 'actual',\n estimate: 'estimate',\n standardized: 'standardized',\n /** Estimated earnings per share of the next release */\n get future_eps(): number {\n return nextEarnings()?.estimate ?? NaN;\n },\n /** Estimated revenue of the next release */\n get future_revenue(): number {\n return nextEarnings()?.revenueEstimate ?? NaN;\n },\n /** Time of the next release (ms) */\n get future_time(): number {\n return nextEarnings()?.time ?? NaN;\n },\n /** End of the fiscal period of the next release (ms) */\n get future_period_end_time(): number {\n return nextEarnings()?.periodEnd ?? NaN;\n },\n} as const;\n\n/** The first event after the current time of the run in the chart symbol's list, when the host gives the announced ones. */\nfunction nextEvent<K extends 'dividends' | 'earnings'>(kind: K): NonNullable<SymbolEvents[K]>[number] | undefined {\n const events = symbolEvents('');\n if (!Object.keys(events).length) return undefined;\n if (!events.future?.[kind]) throw new Error(`${kind}.future_*: the announced ${kind} of ${chartTickerid()} are not known.`);\n return (events[kind] as Array<{ time: number }> | undefined)?.find((e) => e.time > runNow) as NonNullable<SymbolEvents[K]>[number] | undefined;\n}\nconst nextDividend = (): DividendEvent | undefined => nextEvent('dividends');\nconst nextEarnings = (): EarningsEvent | undefined => nextEvent('earnings');\n\nconst DIVIDENDS_PARAMETERS = ['ticker', 'field', 'gaps', 'lookahead', 'ignore_invalid_symbol', 'currency'] as const;\nconst SPLITS_PARAMETERS = ['ticker', 'field', 'gaps', 'lookahead', 'ignore_invalid_symbol'] as const;\n\n/** Named arguments of `request.dividends` / `request.earnings` (`request.splits` has no `currency`). */\nexport interface EventRequestArgs {\n ticker?: string;\n field?: string;\n gaps?: string;\n lookahead?: string;\n ignore_invalid_symbol?: boolean;\n currency?: string;\n}\n\ntype EventRequestCall =\n | [ticker: string, field?: string, gaps?: string, lookahead?: string, ignore_invalid_symbol?: boolean, currency?: string]\n | [ticker: string, field: string, args: EventRequestArgs]\n | [ticker: string, args: EventRequestArgs]\n | [args: EventRequestArgs & { ticker: string }];\n\n/**\n * PineScript `request.dividends(ticker, field, gaps, lookahead, ignore_invalid_symbol, currency)`: the dividend per\n * share (`dividends.net`, default, or `dividends.gross`) as declared, from the bar after its ex-date's day (see\n * `security/events`). na before the first dividend. The events come from `ChartContext.events`.\n */\nfunction dividendsCall(...args: EventRequestCall): Series {\n const a = namedArguments('request.dividends', DIVIDENDS_PARAMETERS, args);\n unsupportedSecurityArgs('request.dividends', a[5], undefined);\n const ticker = (a[0] as string | undefined) ?? '';\n const field = (a[1] as string | undefined) ?? dividends.net;\n if (field !== dividends.net && field !== dividends.gross) throw new Error(`request.dividends(): unknown field \"${field}\": dividends.net or dividends.gross.`);\n const list = symbolEvents(ticker).dividends ?? [];\n const values = field === dividends.gross ? list.map((d) => d.gross ?? d.net) : eventField(list, 'net', 'request.dividends', ticker);\n return eventSeries(list.map((d) => d.time), values, a[2] as string | undefined, a[3] as string | undefined);\n}\n\n/**\n * PineScript `request.splits(ticker, field, gaps, lookahead, ignore_invalid_symbol)`: the numerator\n * (`splits.numerator`) or the denominator (`splits.denominator`) of the last split, from the bar after its day.\n */\nfunction splitsCall(...args: EventRequestCall): Series {\n const a = namedArguments('request.splits', SPLITS_PARAMETERS, args);\n const ticker = (a[0] as string | undefined) ?? '';\n const field = a[1] as string | undefined;\n if (field !== splits.numerator && field !== splits.denominator) {\n throw new Error('request.splits(): the field is splits.numerator or splits.denominator.');\n }\n const list = symbolEvents(ticker).splits ?? [];\n return eventSeries(list.map((s) => s.time), eventField(list, field, 'request.splits', ticker), a[2] as string | undefined, a[3] as string | undefined);\n}\n\n/**\n * PineScript `request.earnings(ticker, field, gaps, lookahead, ignore_invalid_symbol, currency)`: earnings per share of\n * the last release (`earnings.actual`, default, `earnings.estimate` or `earnings.standardized`), from the bar after the\n * period of the chart timeframe it was published in (the next day on a daily chart).\n */\nfunction earningsCall(...args: EventRequestCall): Series {\n const a = namedArguments('request.earnings', DIVIDENDS_PARAMETERS, args);\n unsupportedSecurityArgs('request.earnings', a[5], undefined);\n const ticker = (a[0] as string | undefined) ?? '';\n const field = (a[1] as string | undefined) ?? earnings.actual;\n if (field !== earnings.actual && field !== earnings.estimate && field !== earnings.standardized) {\n throw new Error(`request.earnings(): unknown field \"${field}\": earnings.actual, earnings.estimate or earnings.standardized.`);\n }\n // announced releases still to come have no values yet\n const list = (symbolEvents(ticker).earnings ?? []).filter((e) => e.time <= runNow);\n return eventSeries(list.map((e) => e.time), eventField(list, field, 'request.earnings', ticker), a[2] as string | undefined, a[3] as string | undefined);\n}\n\nconst requestMembers = strictNamespace('request', {\n security: securityCall,\n security_lower_tf: securityLowerTfCall,\n seed: seedCall,\n dividends: dividendsCall,\n splits: splitsCall,\n earnings: earningsCall,\n});\n/**\n * Data from other symbols, timeframes and sources: `request.security` (another symbol or timeframe),\n * `request.security_lower_tf` (the lower-timeframe bars inside each bar), `request.seed` (a separately published data series),\n * dividends, splits and earnings. Call it before any `eachBar()` loop.\n * @example\n * ```js\n * const dailyClose = request.security(\"\", \"D\", () => close);\n * plot(dailyClose, \"Daily close\");\n * ```\n */\nexport const request: RequestNamespace = requestMembers;\nsameKeys<typeof requestMembers, RequestNamespace>(true);\n\n// \u2500\u2500 Drawing objects \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// The drawing namespaces come from this bundle so that they share the registry that\n// executeScript() resets. `line.all` etc. are read like PineScript variables.\n\n/** PineScript `line.*`; `line.all` lists the live lines in creation order. */\n// \u2500\u2500 Drawing namespaces (named arguments, Series arguments in bar loops) \u2500\u2500\u2500\u2500\u2500\u2500\n\ntype Numeric = number | Series;\n/** A function whose number parameters also take a Series (read on the current bar inside a bar loop). */\ntype WithSeries<F> = F extends (...args: infer A) => infer R\n ? (...args: { [K in keyof A]: number extends A[K] ? A[K] | Series : A[K] }) => R\n : never;\ntype ScriptDrawing<T> = { [K in keyof T]: T[K] extends (...args: never[]) => unknown ? T[K] & WithSeries<T[K]> : T[K] };\ntype Colour = string | undefined;\n\n/** Named arguments of `label.new` (PineScript parameter names). */\nexport interface LabelNewArgs {\n x?: Numeric;\n y?: Numeric;\n point?: ChartPoint;\n text?: string;\n xloc?: 'bar_index' | 'bar_time' | 'pane';\n yloc?: 'price' | 'abovebar' | 'belowbar';\n color?: Colour;\n style?: NonNullable<Label['style']>;\n textcolor?: Colour;\n size?: string | number;\n textalign?: 'left' | 'center' | 'right';\n tooltip?: string;\n text_font_family?: 'default' | 'monospace';\n force_overlay?: boolean;\n text_formatting?: number;\n}\n\n/** Named arguments of `line.new`. */\nexport interface LineNewArgs {\n x1?: Numeric;\n y1?: Numeric;\n x2?: Numeric;\n y2?: Numeric;\n first_point?: ChartPoint;\n second_point?: ChartPoint;\n xloc?: 'bar_index' | 'bar_time' | 'pane';\n extend?: 'none' | 'left' | 'right' | 'both';\n color?: Colour;\n style?: 'solid' | 'dotted' | 'dashed' | 'arrow_left' | 'arrow_right' | 'arrow_both';\n width?: Numeric;\n force_overlay?: boolean;\n}\n\n/** Named arguments of `box.new`. */\nexport interface BoxNewArgs {\n left?: Numeric;\n top?: Numeric;\n right?: Numeric;\n bottom?: Numeric;\n top_left?: ChartPoint;\n bottom_right?: ChartPoint;\n border_color?: Colour;\n border_width?: Numeric;\n border_style?: 'solid' | 'dotted' | 'dashed';\n extend?: 'none' | 'left' | 'right' | 'both';\n xloc?: 'bar_index' | 'bar_time' | 'pane';\n bgcolor?: Colour;\n text?: string;\n text_size?: string | number;\n text_color?: Colour;\n text_halign?: 'left' | 'center' | 'right';\n text_valign?: 'top' | 'center' | 'bottom';\n text_wrap?: 'none' | 'auto';\n text_font_family?: 'default' | 'monospace';\n force_overlay?: boolean;\n text_formatting?: number;\n}\n\n/** Named arguments of `table.new`. */\nexport interface TableNewArgs {\n position?: string;\n columns?: number;\n rows?: number;\n bgcolor?: Colour;\n frame_color?: Colour;\n frame_width?: number;\n border_color?: Colour;\n border_width?: number;\n force_overlay?: boolean;\n}\n\n/** Named arguments of `table.cell`. */\nexport interface TableCellArgs {\n table_id?: Table;\n column?: number;\n row?: number;\n text?: string;\n width?: number;\n height?: number;\n text_color?: Colour;\n text_halign?: 'left' | 'center' | 'right';\n text_valign?: 'top' | 'center' | 'bottom';\n text_size?: string | number;\n bgcolor?: Colour;\n tooltip?: string;\n text_font_family?: 'default' | 'monospace';\n text_formatting?: number;\n}\n\n/** Named arguments of `polyline.new`. */\nexport interface PolylineNewArgs {\n points?: ChartPoint[];\n curved?: boolean;\n closed?: boolean;\n xloc?: 'bar_index' | 'bar_time' | 'pane';\n line_color?: Colour;\n fill_color?: Colour | null;\n line_style?: 'solid' | 'dotted' | 'dashed';\n line_width?: number;\n force_overlay?: boolean;\n}\n\n/** Named arguments of `linefill.new`. */\nexport interface LinefillNewArgs {\n line1?: Line;\n line2?: Line;\n color?: Colour;\n}\n\nconst loopBar = (): number => currentBar;\n\n/** Wraps a drawing namespace and keeps its `all` getter (the live drawings in creation order). */\n/** A drawing namespace of scripts: the members of `T`, and `all`. */\ntype DrawingNamespace<T, D> = Omit<ScriptDrawing<T>, 'all'> & {\n /** The live drawings of this kind, oldest first (a new array on each read). */\n readonly all: D[];\n};\n\nfunction drawings<T extends Record<string, unknown>, D>(name: string, members: T, all: () => D[]): DrawingNamespace<T, D> {\n const out = drawingNamespace(name, members, loopBar) as ScriptDrawing<T>;\n return Object.defineProperty(out, 'all', { get: all, enumerable: true }) as DrawingNamespace<T, D>;\n}\n\n// The members are typed by their modules, so that the editor shows each function's documentation.\nconst lineNs: DrawingNamespace<typeof lineCore & typeof pineConstants.lineStyles, Line> = drawings(\n 'line',\n { ...lineCore, ...pineConstants.lineStyles },\n () => lineCore.all()\n);\n/**\n * Lines between two chart points: `line.new()` draws one, `line.set_*` / `line.get_*` move and read it, `line.style_*`\n * are its styles, `line.all` lists the live lines.\n */\nexport const line = lineNs as typeof lineNs & {\n new: ((args: LineNewArgs) => Line) &\n ((x1: Numeric, y1: Numeric, x2: Numeric, y2: Numeric, args: LineNewArgs) => Line) &\n ((first_point: ChartPoint, second_point: ChartPoint, args: LineNewArgs) => Line);\n};\n\nconst labelNs: DrawingNamespace<typeof labelCore & typeof pineConstants.labelStyles, Label> = drawings(\n 'label',\n { ...labelCore, ...pineConstants.labelStyles },\n () => labelCore.all()\n);\n/**\n * Text boxes and shapes at a chart point: `label.new()` draws one, `label.set_*` / `label.get_*` change and read it,\n * `label.style_*` are its styles, `label.all` lists the live labels.\n */\nexport const label = labelNs as typeof labelNs & {\n new: ((args: LabelNewArgs) => Label) &\n ((x: Numeric, y: Numeric, args: LabelNewArgs) => Label) &\n ((x: Numeric, y: Numeric, text: string, args: LabelNewArgs) => Label) &\n ((point: ChartPoint, args: LabelNewArgs) => Label) &\n ((point: ChartPoint, text: string, args: LabelNewArgs) => Label);\n};\n\nconst boxNs: DrawingNamespace<typeof boxCore, Box> = drawings('box', { ...boxCore }, () => boxCore.all());\n/**\n * Rectangles between two x coordinates and two prices, with optional text: `box.new()` draws one, `box.set_*` /\n * `box.get_*` change and read it, `box.all` lists the live boxes.\n */\nexport const box = boxNs as typeof boxNs & {\n new: ((args: BoxNewArgs) => Box) &\n ((left: Numeric, top: Numeric, right: Numeric, bottom: Numeric, args: BoxNewArgs) => Box) &\n ((top_left: ChartPoint, bottom_right: ChartPoint, args: BoxNewArgs) => Box);\n};\n\nconst linefillNs: DrawingNamespace<typeof linefillCore, Linefill> = drawings('linefill', { ...linefillCore }, () => linefillCore.all());\n/**\n * Colour fills between two lines that follow the lines when they move: `linefill.new()`, `linefill.set_color()`,\n * `linefill.all`.\n */\nexport const linefill = linefillNs as typeof linefillNs & {\n new: ((args: LinefillNewArgs) => Linefill) & ((line1: Line, line2: Line, args: LinefillNewArgs) => Linefill);\n};\n\nconst polylineNs: DrawingNamespace<typeof polylineCore, Polyline> = drawings('polyline', { ...polylineCore }, () => polylineCore.all());\n/**\n * Shapes through many chart points, straight or curved, open or closed and filled: `polyline.new()`,\n * `polyline.delete()`, `polyline.all`.\n */\nexport const polyline = polylineNs as typeof polylineNs & {\n new: ((args: PolylineNewArgs) => Polyline) & ((points: ChartPoint[], args: PolylineNewArgs) => Polyline);\n};\n\nconst tableNs: DrawingNamespace<typeof tableCore, Table> = drawings('table', { ...tableCore }, () => tableCore.all());\n/**\n * Tables fixed at a place of the pane, for values and dashboards: `table.new()` creates one, `table.cell()` fills it,\n * `table.all` lists the live tables. The live tables go to `result.tables`.\n */\nexport const table: TableNamespace = tableNs as typeof tableNs & {\n new: ((args: TableNewArgs) => Table) & ((position: string, columns: number, rows: number, args: TableNewArgs) => Table);\n cell: ((args: TableCellArgs) => void) &\n ((table_id: Table, column: number, row: number, args: TableCellArgs) => void) &\n ((table_id: Table, column: number, row: number, text: string, args: TableCellArgs) => void);\n};\nsameKeys<typeof tableNs, TableNamespace>(true);\n\n/** PineScript `position.*` constants (table positions). */\nexport { position };\n\n/** Text constants: `text.format_*` (bold, italic), `text.align_*` (alignment) and `text.wrap_*` (wrapping). */\nexport const text: typeof textCore = { ...textCore };\n\n// The constant namespaces (`shape.triangleup`, `size.small`, `xloc.bar_time`...), each documented in constants.ts.\nexport { shape, location, size, xloc, yloc, extend, display, format, font, scale, order, currency, adjustment } from './constants.js';\n\n/**\n * PineScript `chart.point.*`. `chart.point.now(price?)` is the point of the current bar\n * (index, time, and `price`, default the close), so it runs inside eachBar().\n */\nexport const chart: ChartNamespace = {\n /** Chart foreground colour (PineScript `chart.fg_color`), from the chart context. */\n get fg_color(): string {\n return chartText('foregroundColor', 'chart.fg_color');\n },\n /** Chart background colour (PineScript `chart.bg_color`), from the chart context. */\n get bg_color(): string {\n return chartText('backgroundColor', 'chart.bg_color');\n },\n /** Time (ms) of the first bar in view (PineScript `chart.left_visible_bar_time`), from the chart context; without it,\n * of the first bar. */\n get left_visible_bar_time(): number {\n return visibleBarTime(chartCtx.leftVisibleBarTime, 0);\n },\n /** Time (ms) of the last bar in view (PineScript `chart.right_visible_bar_time`), from the chart context; without it,\n * of the last bar. */\n get right_visible_bar_time(): number {\n return visibleBarTime(chartCtx.rightVisibleBarTime, ctxBars.bars.length - 1);\n },\n /** The chart is not one of the types below (PineScript `chart.is_standard`). */\n get is_standard(): boolean {\n return chartTypeIs('standard');\n },\n get is_heikinashi(): boolean {\n return chartTypeIs('heikinashi');\n },\n get is_renko(): boolean {\n return chartTypeIs('renko');\n },\n get is_kagi(): boolean {\n return chartTypeIs('kagi');\n },\n get is_linebreak(): boolean {\n return chartTypeIs('linebreak');\n },\n get is_pnf(): boolean {\n return chartTypeIs('pnf');\n },\n get is_range(): boolean {\n return chartTypeIs('range');\n },\n point: {\n ...chartPointCore,\n now(price?: number): ChartPoint {\n collector();\n if (currentBar < 0) {\n throw new Error('chart.point.now() needs a current bar: call it inside eachBar().');\n }\n const bar = ctxBars.bars[currentBar]!;\n return chartPointCore.new_point(barTime(bar), currentBar, price ?? bar.close);\n },\n },\n};\n\n/**\n * Makes a Series from an array of numbers, one per bar (oldest first), e.g. values collected inside `eachBar()`.\n * @param values - One value per bar; NaN is na.\n * @returns Series of the values.\n * @example\n * ```js\n * const ranges = [];\n * eachBar((c) => { ranges.push(c.high - c.low); });\n * plot(seriesOf(ranges), \"Range\");\n * ```\n */\nexport function seriesOf(values: number[]): Series {\n collector();\n return Series.fromArray(ctxBars, values);\n}\n\n/**\n * Declares a condition users can create an alert on (in the app's alert dialog). It does not send an alert itself.\n * @param condition - Series that is true (non-zero) on the bars where the alert fires.\n * @param title - Name of the condition in the alert dialog.\n * @param message - Default text of the alert. Default: the title.\n * @example\n * ```js\n * const cross = ta.crossover(close, ta.sma(close, 50));\n * alertcondition(cross, \"Price above SMA 50\", \"Close crossed above its 50-bar average\");\n * ```\n */\nexport function alertcondition(condition: Series, title: string, message?: string): void {\n const c = collector();\n const id = `alert${c.alertConfig.length}`;\n c.alertConfig.push({ id, title, message });\n const values = condition.toArray();\n const b = ctxBars.bars;\n const times: number[] = [];\n for (let i = 0; i < values.length && i < b.length; i++) {\n const v = values[i]!;\n if (!isNA(v) && v !== 0) times.push(b[i]!.time as number);\n }\n const last = values.length ? values[values.length - 1]! : NaN;\n c.alerts.push({ id, title, message, triggered: !isNA(last) && last !== 0, times });\n}\n\nconst ALERT_FREQUENCIES: readonly AlertFrequency[] = ['all', 'once_per_bar', 'once_per_bar_close'];\n\n/**\n * PineScript `alert(message, freq)`, with the `alert.freq_*` constants: the calls are collected per bar with their\n * message and frequency (`result.alertCalls`) for the host's alert engine, which fires the ones made on the realtime\n * bar. Called inside eachBar() / strategy.eachBar() it is a call on the current bar; at the top level of the script\n * (which PineScript runs on every bar) it is a call on every bar, `message` then being a text or one text per bar\n * (a bar whose text is na makes no call). Default frequency: `alert.freq_once_per_bar`.\n */\nfunction alertImpl(message: string | ReadonlyArray<string | undefined>, freq: AlertFrequency = 'once_per_bar'): void {\n const c = collector();\n if (!ALERT_FREQUENCIES.includes(freq)) {\n throw new Error(`alert(): freq must be alert.freq_all, alert.freq_once_per_bar or alert.freq_once_per_bar_close, not ${String(freq)}.`);\n }\n c.hasAlertFunction = true;\n const b = ctxBars.bars;\n const textAt = (i: number): string | undefined => (typeof message === 'string' ? message : message[i]);\n const call = (i: number): void => {\n const text = textAt(i);\n if (text === undefined || text === null) return;\n c.alertCalls.push({ time: b[i]!.time as number, message: String(text), freq });\n };\n if (currentBar >= 0) call(currentBar);\n else for (let i = 0; i < b.length; i++) call(i);\n}\n\nconst alertMembers = Object.assign(alertImpl, {\n freq_all: 'all',\n freq_once_per_bar: 'once_per_bar',\n freq_once_per_bar_close: 'once_per_bar_close',\n} as const);\n/**\n * Sends an alert message while the script runs (to the alerts set on the script), with the `alert.freq_*`\n * constants for how often it may fire.\n * @example\n * ```js\n * eachBar((c) => {\n * if (c.get(close) > c.get(high, 1)) alert(\"New high\", alert.freq_once_per_bar_close);\n * });\n * ```\n */\nexport const alert: AlertApi = alertMembers;\nsameKeys<typeof alertMembers, AlertApi>(true);\n\n// \u2500\u2500 Logs (log.info / log.warning / log.error) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The level of a log message. */\nexport type LogLevel = 'info' | 'warning' | 'error';\n\n/** One log.*() message: the bar it was made on (index, and time as given in the input bars), its level and text, and\n * the line of the script that made it when the host resolves it ({@link setLogLineResolver}). */\nexport interface LogEntry {\n bar: number;\n time: number;\n level: LogLevel;\n message: string;\n line?: number;\n}\n\n/** The most messages a run keeps: the newest ones. */\nexport const MAX_LOG_ENTRIES = 10_000;\n\nlet logLineResolver: ((stack: string) => number | undefined) | null = null;\n\n/**\n * Host-side: how the host finds the line of the script that called log.*(). Scripts never call it.\n * @param resolver - Gets the stack of the call (an Error's `stack`) and gives the line in the script's own source;\n * null (the default): messages have no line.\n */\nexport function setLogLineResolver(resolver: ((stack: string) => number | undefined) | null): void {\n logLineResolver = resolver;\n}\n\nfunction logImpl(level: LogLevel, message: string | ReadonlyArray<string | undefined>, args: unknown[]): void {\n const c = collector();\n const b = ctxBars.bars;\n const line = logLineResolver ? logLineResolver(new Error().stack ?? '') : undefined;\n const add = (i: number): void => {\n const text = typeof message === 'string' ? message : message[i];\n if (text === undefined || text === null) return;\n // A Series argument gives its value on the bar.\n const values = args.map((a) => (a instanceof Series ? a.get(i) : a));\n const entry: LogEntry = {\n bar: i,\n time: b[i]!.time as number,\n level,\n message: args.length ? formatMessage(String(text), values, exchangeTimezone) : String(text),\n };\n if (line !== undefined) entry.line = line;\n c.logs.push(entry);\n };\n if (currentBar >= 0) add(currentBar);\n else for (let i = 0; i < b.length; i++) add(i);\n if (c.logs.length > MAX_LOG_ENTRIES * 2) c.logs.splice(0, c.logs.length - MAX_LOG_ENTRIES);\n}\n\nconst logMembers = strictNamespace('log', {\n info(message: string | ReadonlyArray<string | undefined>, ...args: unknown[]): void {\n logImpl('info', message, args);\n },\n warning(message: string | ReadonlyArray<string | undefined>, ...args: unknown[]): void {\n logImpl('warning', message, args);\n },\n error(message: string | ReadonlyArray<string | undefined>, ...args: unknown[]): void {\n logImpl('error', message, args);\n },\n});\n/**\n * Messages for the logs panel: `log.info`, `log.warning` and `log.error`. Inside `eachBar()` a call makes a message on\n * the current bar; at the top level, one message per bar. With arguments the message is a `str.format()` pattern.\n * @example\n * ```js\n * eachBar((c) => {\n * if (c.get(volume) > 2 * c.get(ta.sma(volume, 20))) log.info(\"Volume spike: {0}\", c.get(volume));\n * });\n * ```\n */\nexport const log: LogNamespace = logMembers;\nsameKeys<typeof logMembers, LogNamespace>(true);\n\n/** The messages of a resumed run calculated from bar `from`: those of the run before on the bars before `from`, then the\n * new ones on the bars from `from` (the top-level log calls of a resumed run make them again on every bar). */\nfunction resumedLogs(before: LogEntry[] | undefined, now: LogEntry[] | undefined, from: number): LogEntry[] | undefined {\n const kept = (before ?? []).filter((e) => e.bar < from);\n const logs = kept.concat((now ?? []).filter((e) => e.bar >= from));\n return logs.length ? logs.slice(-MAX_LOG_ENTRIES) : undefined;\n}\n\n// \u2500\u2500 Convenience re-exports \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport { Series, BarData };\nexport { STRATEGY_DEFAULTS } from '../strategy/index.js';\nexport type {\n StrategyCloseAllOptions,\n StrategyCloseOptions,\n StrategyCommissionType,\n StrategyDirection,\n StrategyEngine,\n StrategyEntryOptions,\n StrategyExitOptions,\n StrategyNumberVariable,\n StrategyOcaType,\n StrategyOptions,\n StrategyProperties,\n StrategyQtyType,\n StrategyRiskDirection,\n StrategyRiskRule,\n StrategyRiskValueType,\n StrategyTextVariable,\n StrategyTrade,\n StrategyVariable,\n} from '../strategy/index.js';\n\nconst { saveRandom: _saveRandom, restoreRandom: _restoreRandom, ...mathScript } = mathCore;\nvoid _saveRandom;\nvoid _restoreRandom;\n/**\n * Math functions and constants for numbers and Series: rounding, min and max, powers and logarithms, trigonometry,\n * random numbers, `math.pi`... A Series argument gives a Series, numbers give a number. `math.round_to_mintick`\n * uses the symbol's tick size.\n * @example\n * ```js\n * const range = math.abs(close.sub(open));\n * plot(math.round(ta.sma(range, 10), 2), \"Body\");\n * ```\n */\nexport const math: Omit<typeof mathCore, 'saveRandom' | 'restoreRandom'> = strictNamespace('math', {\n ...mathScript,\n // the generators start again on each run: a resumed run would draw other numbers (#206)\n random: ((min?: number, max?: number, seed?: number) => {\n incremental.nonIncremental('math.random');\n return mathCore.random(min, max, seed);\n }) as typeof mathCore.random,\n round_to_mintick: ((number: number | Series, mintick?: number) => {\n const tick = mintick ?? syminfo.mintick;\n return number instanceof Series ? mathCore.round_to_mintick(number, tick) : mathCore.round_to_mintick(number, tick);\n }) as typeof mathCore.round_to_mintick,\n});\n// \u2500\u2500 calc: plain-English names \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** A number as a Series of the bars of the run. */\nconst asSeries = (v: Series | number): Series => (typeof v === 'number' ? Series.constant(ctxBars, v) : v);\n\n/** The kinds of `calc.average()`. */\nconst AVERAGE_KINDS: Record<string, (s: Series, n: number) => Series> = {\n simple: (s, n) => taSeries.sma(s, n),\n exponential: (s, n) => taSeries.ema(s, n),\n weighted: (s, n) => taSeries.wma(s, n),\n smoothed: (s, n) => taSeries.rma(s, n),\n hull: (s, n) => taSeries.hma(s, n),\n 'volume-weighted': (s, n) => ta.vwma(s, n),\n};\n\nfunction checkLength(fn: string, length: unknown): number {\n if (typeof length !== 'number' || !Number.isInteger(length) || length < 1) {\n throw new ScriptError(`calc.${fn}(): the length is a whole number of bars, 1 or more, got ${shown(length)}.`);\n }\n return length;\n}\n\n/** The conditions of `calc.all()` / `calc.any()` as Series; at least one is needed. */\nfunction conditionsOf(name: string, conditions: Array<Series | number>): Series[] {\n if (!conditions.length) throw new ScriptError(`${name}(): give at least one condition, e.g. ${name}(close.gt(open), volume.gt(0)).`);\n return conditions.map(asSeries);\n}\n\nconst calcMembers = strictNamespace('calc', outsideBarLoops({\n /** Moving average of the last `length` values: kind 'simple' (default), 'exponential', 'weighted', 'smoothed', 'hull' or 'volume-weighted'. */\n average(source: Series | number, length: number, kind: string = 'simple'): Series {\n const fn = AVERAGE_KINDS[kind];\n if (!fn) throw new ScriptError(`calc.average(): the kind is one of ${Object.keys(AVERAGE_KINDS).map((k) => `'${k}'`).join(', ')}, got ${shown(kind)}.`);\n return fn(asSeries(source), checkLength('average', length));\n },\n /** 1 on the bar where `a` crosses above `b`. */\n crossesAbove: (a: Series | number, b: Series | number): Series => ta.crossover(asSeries(a), b),\n /** 1 on the bar where `a` crosses below `b`. */\n crossesBelow: (a: Series | number, b: Series | number): Series => ta.crossunder(asSeries(a), b),\n /** 1 on the bar where `a` and `b` cross, either way. */\n crosses: (a: Series | number, b: Series | number): Series => ta.cross(asSeries(a), asSeries(b)),\n /** 1 where `a` is above `b`. */\n above: (a: Series | number, b: Series | number): Series => asSeries(a).gt(b),\n /** 1 where `a` is below `b`. */\n below: (a: Series | number, b: Series | number): Series => asSeries(a).lt(b),\n /** 1 where `value` is between `low` and `high` (both included). */\n between: (value: Series | number, lowLimit: Series | number, highLimit: Series | number): Series =>\n asSeries(value).gte(lowLimit).and(asSeries(value).lte(highLimit)),\n /** The value `bars` bars before (1: the previous bar). */\n previous: (source: Series | number, bars: number = 1): Series => asSeries(source).offset(checkLength('previous', bars)),\n /** The difference with the value `bars` bars before. */\n change: (source: Series | number, bars: number = 1): Series => taSeries.change(asSeries(source), checkLength('change', bars)),\n /** The change in percent since `bars` bars before. */\n percentChange: (source: Series | number, bars: number = 1): Series => {\n const s = asSeries(source);\n const before = s.offset(checkLength('percentChange', bars));\n return s.sub(before).div(before).mul(100);\n },\n /** The highest value of the last `length` bars. */\n highest: (source: Series | number, length: number): Series => ta.highest(asSeries(source), checkLength('highest', length)),\n /** The lowest value of the last `length` bars. */\n lowest: (source: Series | number, length: number): Series => ta.lowest(asSeries(source), checkLength('lowest', length)),\n /** 1 when the value rose on each of the last `bars` bars. */\n isRising: (source: Series | number, bars: number = 1): Series => taSeries.rising(asSeries(source), checkLength('isRising', bars)),\n /** 1 when the value fell on each of the last `bars` bars. */\n isFalling: (source: Series | number, bars: number = 1): Series => taSeries.falling(asSeries(source), checkLength('isFalling', bars)),\n /** Standard deviation of the last `length` values. */\n standardDeviation: (source: Series | number, length: number): Series => taSeries.stdev(asSeries(source), checkLength('standardDeviation', length)),\n /** `whenTrue` where the condition holds, else `whenFalse`. */\n ifElse: (condition: Series | number, whenTrue: Series | number, whenFalse: Series | number): Series => asSeries(condition).iff(whenTrue, whenFalse),\n /** 1 where every condition holds. */\n all: (...conditions: Array<Series | number>): Series => conditionsOf('calc.all', conditions).reduce((x, y) => x.and(y)),\n /** 1 where one of the conditions holds. */\n any: (...conditions: Array<Series | number>): Series => conditionsOf('calc.any', conditions).reduce((x, y) => x.or(y)),\n}, 'calc'));\n/**\n * Plain-English names for the most used calculations (`calc.average`, `calc.crossesAbove`...), beside the `ta.*` ones.\n * They take Series or numbers and give a Series; a condition gives 1 where true and 0 where false.\n */\nexport const calc: CalcNamespace = calcMembers;\nsameKeys<typeof calcMembers, CalcNamespace>(true);\n\n/**\n * Comparisons of two numbers with a tolerance of 1e-10 (`compare.eq(0.1 + 0.2, 0.3)` is true), for the plain numbers\n * of a bar loop.\n */\nexport const compare = compareCore;\nexport { isInputActive } from '../runtime/input-active.js';\nexport type {\n Bar,\n IndicatorResult,\n TimeValue,\n InputConfig,\n InputCondition,\n PlotConfig,\n HLineConfig,\n FillConfig,\n ShapeConfig,\n ArrowConfig,\n BarColorConfig,\n CandleConfig,\n MarkerData,\n MarkerPosition,\n MarkerShape,\n ArrowData,\n BarColorData,\n BgColorData,\n PlotCandleData,\n PlotBarData,\n LabelData,\n LabelStyle,\n LineDrawingData,\n BoxData,\n LinefillData,\n PolylineData,\n TableData,\n TableCellData,\n TableMergeData,\n TablePosition,\n MarkerLocation,\n MarkerSize,\n PineSize,\n ShapeStyle,\n};\n\n// \u2500\u2500 defineIndicator \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport {\n defineIndicator,\n type DefineIndicatorOptions,\n type IndicatorCalculation,\n type IndicatorDefinition,\n type IndicatorLiveRun,\n} from './define.js';\nexport { formula, evaluateFormula, FORMULA_FUNCTIONS, type FormulaVariables } from './formula.js';\nexport {\n defineIndicatorFromJson,\n indicatorBodyFromJson,\n checkIndicatorJson,\n type Ind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EAAE,IAAI,UAAU,SAAS;AAAA;AAAA,EAElJ,KAAK,IAAI,eAA+C,aAAa,YAAY,UAAU,EAAE,OAAO,CAAC,GAAG,MAAM,EAAE,IAAI,CAAC,CAAC;AAAA;AAAA,EAEtH,KAAK,IAAI,eAA+C,aAAa,YAAY,UAAU,EAAE,OAAO,CAAC,GAAG,MAAM,EAAE,GAAG,CAAC,CAAC;AACvH,GAAG,MAAM,CAAC;AAKH,MAAM,OAAsB;AACnC,SAA4C,IAAI;AAMzC,MAAM,UAAU;",
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview PineScript-style script API \u2014 write an indicator as a flat\n * script instead of the explicit calculate() convention.\n *\n * ```typescript\n * import { indicator, input, plot, ta } from 'oakscriptjs/script';\n *\n * indicator('My SMA', { overlay: true });\n * const length = input.int(20, 'Length', { minval: 1 });\n * const src = input.source('close', 'Source');\n * plot(ta.sma(src, length), 'SMA', { color: '#2962FF' });\n * ```\n *\n * Execution model: the host calls {@link executeScript} with the script body,\n * the bars and the current input values. Declaration calls (indicator, input.*,\n * plot, hline, fill, alertcondition, alert) run as the body executes and are collected\n * into a {@link ScriptRunResult}: the declarative configs (inputConfig,\n * plotConfig, hlineConfig, fillConfig) plus an IndicatorResult with the plot\n * data. Re-running the body with new bars or inputs is PineScript's\n * recalculation model.\n *\n * `input.*` is idempotent like PineScript: it declares the input AND returns\n * its current value (the host-supplied override, else the default).\n *\n * The OHLCV builtins (open/high/low/close/volume/hl2/hlc3/ohlc4/hlcc4) are\n * Series bound to a module-level BarData that the host swaps per run, so\n * derived Series memoize between identical runs and recompute when the bars\n * version bumps.\n *\n * One script executes at a time (module-level context) \u2014 hosts that run many\n * scripts must serialize executions, which a Web Worker does naturally.\n *\n * @module script\n */\n\nimport type { Bar } from '../types/index.js';\nimport type {\n ArrowData,\n BarColorData,\n BgColorData,\n BoxData,\n FillData,\n FillGradient,\n IndicatorResult,\n LabelData,\n LabelStyle,\n LineDrawingData,\n LinefillData,\n MarkerData,\n MarkerLocation,\n MarkerPosition,\n MarkerShape,\n MarkerSize,\n PineSize,\n PlotBarData,\n PlotCandleData,\n PolylineData,\n ShapeStyle,\n TableCellData,\n TableData,\n TableMergeData,\n TablePosition,\n TimeValue,\n} from '../types/metadata.js';\nimport type {\n ArrowConfig,\n BarColorConfig,\n CandleConfig,\n FillConfig,\n HLineConfig,\n InputConfig,\n InputCondition,\n PlotConfig,\n ShapeConfig,\n} from '../runtime/types.js';\nimport { BarData, Series, MAX_BARS_BACK, historyError } from '../runtime/series.js';\nimport * as taSeries from '../ta-series.js';\nimport type { TaNamespace } from './api/ta.js';\nimport type { StrategyNamespace } from './api/strategy.js';\nimport type {\n BarmergeNamespace,\n BarstateNamespace,\n ChartNamespace,\n DividendsNamespace,\n EarningsNamespace,\n RequestNamespace,\n SessionNamespace,\n SplitsNamespace,\n SyminfoNamespace,\n TickerNamespace,\n TimeframeNamespace,\n} from './api/context.js';\nimport type { CalcNamespace } from './api/calc.js';\nimport type { ColorNamespace } from './api/color.js';\nimport type { LogNamespace } from './api/log.js';\nimport type { AlertApi } from './api/alert.js';\nimport type { TableNamespace } from './api/table.js';\nimport { taStep, type BarStep } from '../ta/step.js';\nimport * as incremental from './incremental.js';\nimport { outerWrites } from './closure-writes.js';\nimport * as pineConstants from './constants.js';\nimport { drawingNamespace, isPlainObject, namedArguments, unknownArgument } from './drawing-args.js';\nimport * as colorCore from '../color/index.js';\nimport * as compareCore from '../compare/index.js';\nimport { inputColorDefault, isColorText } from '../color/parse.js';\nimport { fixnan as fixnanValues, isNA, nz as nzValue } from '../utils/index.js';\nimport { externalSource } from '../utils/source-resolver.js';\nimport * as lineCore from '../line/index.js';\nimport * as labelCore from '../label/index.js';\nimport * as boxCore from '../box/index.js';\nimport * as linefillCore from '../linefill/index.js';\nimport * as polylineCore from '../polyline/index.js';\nimport * as tableCore from '../table/index.js';\nimport * as chartPointCore from '../chartpoint/index.js';\nimport * as textCore from '../text/index.js';\nimport * as mathCore from '../math/index.js';\nimport {\n createdDrawingKinds,\n droppedDrawings,\n resetDrawings,\n restoreDrawingCheckpoint,\n restoreDrawingState,\n saveDrawingCheckpoint,\n saveDrawingState,\n setDrawingBar,\n setDrawingLimits,\n holdDrawing,\n releaseDrawing,\n type DrawingKind,\n type DrawingVariable,\n} from '../drawing/registry.js';\nexport { holdDrawing, releaseDrawing, type DrawingVariable } from '../drawing/registry.js';\n\n/**\n * A variable that holds one drawing (a line, label, box...) from bar to bar and keeps it alive: the object it holds is\n * never deleted by the `max_*_count` limit of the script. Use it to create one object and move it, instead of a new\n * object on each bar. Assigning another object (or `undefined` for na) releases the one before, which the limit can\n * delete again. Declare it in the script body (outside the bar loops), then read and write `.value` in a bar loop.\n * @param initial - The object held from the start. Default: none (`.value` is `undefined`).\n * @returns A box whose `.value` is the held object, or `undefined`.\n * @example\n * ```js\n * const level = varDrawing();\n * eachBar((c) => {\n * if (c.i === c.n - 1) level.value = line.new(c.i - 20, c.close, c.i, c.close, { color: color.orange });\n * });\n * ```\n */\n// Without an initial object the kind is not known: `.value` is any drawing, so `line.delete(v.value)` checks.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function varDrawing<T extends object = any>(initial?: T): DrawingVariable<T> {\n const box = persist<T | undefined>(initial ? holdDrawing(initial) : undefined);\n return {\n get value() {\n return box.value;\n },\n set value(next: T | undefined) {\n const current = box.value;\n if (next === current) return;\n releaseDrawing(current);\n box.value = next ? holdDrawing(next) : undefined;\n },\n };\n}\nimport { drawingOutputs } from '../drawing/output.js';\nimport * as timeframeCore from '../timeframe/index.js';\nimport * as timeCore from '../time/index.js';\nimport * as strCore from '../str/index.js';\nimport { formatMessage } from '../str/messageformat.js';\nimport { tickScale } from '../str/numberformat.js';\nimport { TradingCalendar, type SessionSpec } from '../session/calendar.js';\nimport { SessionBars, sessionFlags, strayPeriods, type SessionFlags } from '../session/bars.js';\nimport { afterCompletion, heikinAshi, mapToChart, periodsOf, resample } from '../security/resample.js';\nimport { securityLowerTf, securityOther, type OtherSymbolChart } from '../security/other.js';\nimport { eventsOnBars } from '../security/events.js';\nimport { position } from '../types/index.js';\nimport type { Box, ChartPoint, Label, Line, Linefill, Polyline, Table } from '../types/index.js';\nimport {\n STRATEGY_CONSTANTS,\n STRATEGY_DEFAULTS,\n STRATEGY_NUMBER_VARIABLES,\n STRATEGY_TEXT_VARIABLES,\n type StrategyCloseAllOptions,\n type StrategyCloseOptions,\n type StrategyDirection,\n type StrategyEngine,\n type StrategyEntryOptions,\n type StrategyExitOptions,\n type StrategyNumberVariable,\n type StrategyOptions,\n type StrategyProperties,\n type StrategyRiskDirection,\n type StrategyRiskRule,\n type StrategyRiskValueType,\n type StrategyTextVariable,\n type StrategyTrade,\n type StrategyVariable,\n} from '../strategy/index.js';\nimport { sessionPeriods, type SessionPeriods } from '../session/context.js';\n\n/** Everything one run of a script produced. */\nexport interface ScriptRunResult {\n metadata: {\n title: string;\n shortTitle?: string;\n overlay: boolean;\n precision?: number;\n format?: string;\n scale?: 'right' | 'left' | 'none';\n /** indicator(..., { pane }) when the script gives it (not PineScript); `overlay` is the pane it gave. */\n pane?: 'price' | 'separate' | 'auto';\n };\n inputConfig: InputConfig[];\n plotConfig: PlotConfig[];\n hlineConfig: HLineConfig[];\n fillConfig: FillConfig[];\n shapeConfig: ShapeConfig[];\n arrowConfig: ArrowConfig[];\n barColorConfig: BarColorConfig[];\n /** plotcandle() / plotbar() declarations */\n candleConfig: CandleConfig[];\n /**\n * The kinds of drawing objects (label.new, line.new, box.new, linefill.new, polyline.new, table.new) the run\n * created, even the ones deleted since: the drawing groups a user can show or hide.\n */\n drawingKinds: DrawingKind[];\n /**\n * The plot(), plotshape(), plotchar(), plotarrow(), plotcandle() and plotbar() declarations in the order the\n * script made them (the id of each in its own config). PineScript numbers a script's outputs in this order.\n */\n outputs: ScriptOutput[];\n defaultInputs: Record<string, unknown>;\n alertConfig: AlertConditionConfig[];\n /** Strategy properties (declared values, else the PineScript defaults) when the script declares strategy(). */\n strategyConfig?: StrategyProperties;\n /**\n * The renderable output: plots keyed by plotConfig ids, plot-pair fills, markers, arrows, background and bar\n * colours, candles and bars, and the drawings (labels, lines, boxes, linefills, polylines, tables) alive after the\n * last bar. `outputValues`: per plotshape() / plotchar() / plotarrow() id, the value of its series on each bar where\n * it is not na (a condition gives 1 or 0), at the bar it was computed on (the offset not applied).\n */\n result: IndicatorResult & { alerts?: AlertState[]; alertCalls?: AlertCall[]; outputValues?: Record<string, TimeValue[]>; logs?: LogEntry[] };\n /** The script called alert() during the run (PineScript `hasAlertFunction` is known at compile time: a host that\n * needs it before any bar runs reads the source). */\n hasAlertFunction: boolean;\n /** The script read `chart.left_visible_bar_time` or `chart.right_visible_bar_time`: it has to be calculated again when\n * the visible range of the chart changes. */\n usesVisibleRange: boolean;\n /**\n * Things the run did that a script usually does not mean, in plain words: drawings deleted because there were more\n * than the maximum count (`indicator(max_labels_count)`...). Empty when there is nothing to say.\n */\n warnings: string[];\n}\n\nexport interface AlertConditionConfig {\n id: string;\n title: string;\n message?: string;\n}\n\n/** Per-run alert evaluation: whether the condition is true on the last bar, and on which bars it is true. */\nexport interface AlertState {\n id: string;\n title: string;\n message?: string;\n triggered: boolean;\n /** Times of the bars (as given in the input bars) on which the condition is true (not na, not 0), oldest first. */\n times: number[];\n}\n\n/** How often an alert() call may trigger the alert (PineScript `alert.freq_*`). */\nexport type AlertFrequency = 'all' | 'once_per_bar' | 'once_per_bar_close';\n\n/** One alert() call: the time of the bar it ran on (as given in the input bars), its message and frequency. */\nexport interface AlertCall {\n time: number;\n message: string;\n freq: AlertFrequency;\n}\n\n/** One output declaration of a script: plot(), plotshape() ('shape'), plotchar() ('char'), plotarrow() ('arrow'),\n * plotcandle() ('candle') or plotbar() ('bar'), with its id in plotConfig / shapeConfig / arrowConfig / candleConfig. */\nexport interface ScriptOutput {\n kind: 'plot' | 'shape' | 'char' | 'arrow' | 'candle' | 'bar';\n id: string;\n title?: string;\n}\n\n/** Handle returned by plot()/hline() so fill() can reference them. */\nexport interface PlotHandle {\n id: string;\n kind: 'plot' | 'hline';\n}\n\ninterface Collector {\n declaration?: 'indicator' | 'strategy';\n title: string;\n shortTitle?: string;\n overlay: boolean;\n precision?: number;\n format?: string;\n /** indicator(..., { scale }): the price scale the script uses. */\n scale?: 'right' | 'left' | 'none';\n inputValues: Record<string, unknown>;\n inputConfig: InputConfig[];\n inputIds: Set<string>;\n defaultInputs: Record<string, unknown>;\n plotConfig: PlotConfig[];\n plots: Record<string, TimeValue[]>;\n hlineConfig: HLineConfig[];\n fills: FillData[];\n fillConfig: FillConfig[];\n shapeConfig: ShapeConfig[];\n markers: MarkerData[];\n outputValues: Record<string, TimeValue[]>;\n arrowConfig: ArrowConfig[];\n arrows: ArrowData[];\n barColorConfig: BarColorConfig[];\n bgColors: BgColorData[];\n barColors: BarColorData[];\n candleConfig: CandleConfig[];\n plotCandles: Record<string, PlotCandleData[]>;\n plotBars: Record<string, PlotBarData[]>;\n outputs: ScriptOutput[];\n alertConfig: AlertConditionConfig[];\n alerts: AlertState[];\n alertCalls: AlertCall[];\n /** log.*() messages of the run. */\n logs: LogEntry[];\n hasAlertFunction: boolean;\n usesVisibleRange: boolean;\n strategy?: StrategyRun;\n /** Strict mode (`ScriptOptions.strict`): mistakes are errors. */\n strict: boolean;\n /** indicator(..., { pane: 'auto' }): the pane is chosen from the plotted values at the end of the run. */\n paneAuto?: boolean;\n /** indicator(..., { pane }) as given. */\n pane?: 'price' | 'separate' | 'auto';\n /** Plot ids taken (`ScriptOptions.plotIds` 'title'). */\n plotIdsTaken?: Set<string>;\n /** Plots that took a colour of the palette so far. */\n paletteUsed?: number;\n}\n\n/** State of the strategy of the current run. */\ninterface StrategyRun {\n properties: StrategyProperties;\n engine?: StrategyEngine;\n /** strategy.eachBar() has run (it runs once per script run). */\n looped: boolean;\n /** Inside the strategy.eachBar() callback. */\n inLoop: boolean;\n}\n\n/** Bars for the current run. Module-level and REUSED across runs so builtins\n * and every Series derived from them keep their version-keyed memoization. */\nconst ctxBars = new BarData([]);\n\nlet ctx: Collector | null = null;\n\nfunction collector(): Collector {\n if (!ctx) {\n throw new Error(\n 'oakscriptjs/script functions can only run inside executeScript() \u2014 ' +\n 'the host (chart/worker) drives script execution.'\n );\n }\n return ctx;\n}\n\nfunction freshCollector(inputValues: Record<string, unknown>, strict = false): Collector {\n return {\n strict,\n title: 'Untitled',\n overlay: false,\n inputValues,\n inputConfig: [],\n inputIds: new Set(),\n defaultInputs: {},\n plotConfig: [],\n plots: {},\n hlineConfig: [],\n fills: [],\n fillConfig: [],\n shapeConfig: [],\n markers: [],\n outputValues: {},\n arrowConfig: [],\n arrows: [],\n barColorConfig: [],\n bgColors: [],\n barColors: [],\n candleConfig: [],\n plotCandles: {},\n plotBars: {},\n outputs: [],\n alertConfig: [],\n alerts: [],\n alertCalls: [],\n logs: [],\n hasAlertFunction: false,\n usesVisibleRange: false,\n };\n}\n\n/** Stable input id from the title (\"ATR / Range Period\" \u2192 \"atr_range_period\"). */\nfunction slugId(title: string | undefined, fallback: string, taken: Set<string>): string {\n const base =\n (title ?? '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '') || fallback;\n let id = base;\n for (let n = 2; taken.has(id); n++) id = `${base}_${n}`;\n taken.add(id);\n return id;\n}\n\n/** A value as it is written in a script, for messages. */\nfunction shown(v: unknown): string {\n if (typeof v === 'string') return JSON.stringify(v);\n if (typeof v === 'number' || typeof v === 'boolean' || v === null || v === undefined) return String(v);\n return Array.isArray(v) ? 'a list' : typeof v === 'object' ? 'an object' : typeof v;\n}\n\n/** Up to three of `names` close to `name` (spelling mistakes), closest first. */\nfunction closeNames(name: string, names: readonly string[]): string[] {\n const bare = (x: string) => x.toLowerCase().replace(/[^a-z0-9]/g, '');\n const same = names.filter((k) => bare(k) === bare(name));\n if (same.length) return same;\n const n = name.toLowerCase();\n const dist = (a: string, b: string): number => {\n const row = Array.from({ length: b.length + 1 }, (_, j) => j);\n for (let i = 1; i <= a.length; i++) {\n let diag = row[0]!;\n row[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const up = row[j]!;\n row[j] = Math.min(up + 1, row[j - 1]! + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));\n diag = up;\n }\n }\n return row[b.length]!;\n };\n return names\n .map((k) => ({ k, d: dist(n, k.toLowerCase()) }))\n .filter(({ k, d }) => d <= Math.max(2, Math.floor(name.length / 3)) || k.toLowerCase().includes(n) || n.includes(k.toLowerCase()))\n .sort((a, b) => a.d - b.d)\n .slice(0, 3)\n .map(({ k }) => k);\n}\n\n/** Strict mode: every input value given by the host has a name the script declares. */\nfunction checkInputNames(c: Collector, inputs: Record<string, unknown>): void {\n const names = c.inputConfig.map((i) => i.id);\n for (const key of Object.keys(inputs)) {\n if (c.inputIds.has(key)) continue;\n const near = closeNames(key, names);\n throw new ScriptError(\n `There is no input \"${key}\".` + (near.length ? ` Did you mean \"${near.join('\", \"')}\"?` : '') +\n (names.length ? ` The inputs are: ${names.join(', ')}.` : ' The script has no inputs.')\n );\n }\n}\n\n/** Strict mode: the value the host gives an input has its type, range and options. */\nfunction checkInputValue(config: InputConfig, id: string, value: unknown): void {\n const name = config.title ? `\"${config.title}\" (${id})` : `\"${id}\"`;\n const fail = (why: string): never => {\n throw new ScriptError(`Input ${name}: ${why}`);\n };\n switch (config.type) {\n case 'int':\n case 'float':\n case 'price':\n case 'time':\n if (typeof value !== 'number' || Number.isNaN(value)) fail(`${shown(value)} is not a number.`);\n if (config.type === 'int' && !Number.isInteger(value)) fail(`${value} is not a whole number.`);\n if (config.min !== undefined && (value as number) < config.min) fail(`${value} is below the minimum, ${config.min}.`);\n if (config.max !== undefined && (value as number) > config.max) fail(`${value} is above the maximum, ${config.max}.`);\n break;\n case 'bool':\n if (typeof value !== 'boolean') fail(`${shown(value)} is not true or false.`);\n break;\n case 'color':\n if (!isColorText(value)) fail(`${shown(value)} is not a colour. Write it as \"#ff0000\" or \"rgba(255, 0, 0, 0.5)\".`);\n break;\n case 'source':\n if (typeof value !== 'string' || (!SOURCES[value] && !externalSource(value))) {\n fail(`${shown(value)} is not a price source. The sources are: ${Object.keys(SOURCES).join(', ')}.`);\n }\n break;\n default:\n if (typeof value !== 'string') fail(`${shown(value)} is not a text.`);\n }\n if (config.options && !config.options.includes(value as string | number)) {\n fail(`${shown(value)} is not one of the choices: ${config.options.map(shown).join(', ')}.`);\n }\n}\n\n/** Strict mode: the named options of a declaration call are known and its colours are colours. */\nfunction checkOptions(fn: string, options: object | undefined, keys: readonly string[], colorKeys: readonly string[] = ['color']): void {\n if (!ctx?.strict || options === undefined) return;\n if (!isPlainObject(options)) throw new ScriptError(`${fn}(): the options are an object, e.g. { color: color.red }.`);\n for (const [key, v] of Object.entries(options)) {\n if (!keys.includes(key)) {\n const near = closeNames(key, keys);\n throw new ScriptError(\n `${fn}(): there is no option \"${key}\".` + (near.length ? ` Did you mean \"${near.join('\", \"')}\"?` : '') +\n ` The options are: ${keys.join(', ')}.`\n );\n }\n if (colorKeys.includes(key)) checkColor(`${fn}(): the ${key}`, v);\n }\n}\n\n/** Strict mode: a colour argument (a colour or per-bar colours; na entries are allowed) holds colours only. */\nfunction checkColor(what: string, v: unknown): void {\n if (v === undefined || v === null) return;\n const bad = Array.isArray(v) ? v.find((x) => x !== undefined && x !== null && x !== '' && !isColorText(x)) : isColorText(v) ? undefined : v;\n if (bad !== undefined) {\n const name = typeof bad === 'string' ? bad.trim().toLowerCase() : '';\n if (/^[a-z]+$/.test(name) && typeof (colorCore as Record<string, unknown>)[name] === 'string') {\n throw new ScriptError(`${what} ${shown(bad)} is a colour name: write color.${name} (without quotes).`);\n }\n throw new ScriptError(`${what} ${shown(bad)} is not a colour. Write a colour as color.red, \"#ff0000\" or \"rgba(255, 0, 0, 0.5)\".`);\n }\n}\n\n/** The warnings of the run that ends (see `ScriptRunResult.warnings`). */\nfunction runWarnings(): string[] {\n const out: string[] = [];\n const option: Record<string, string> = { line: 'max_lines_count', label: 'max_labels_count', box: 'max_boxes_count', polyline: 'max_polylines_count', linefill: 'max_lines_count' };\n for (const [kind, n] of Object.entries(droppedDrawings())) {\n if (!n || kind === 'table') continue;\n out.push(\n `${n} ${kind}${n > 1 ? 's were' : ' was'} deleted because the script made more than the maximum number of ${kind}s; ` +\n `the oldest go first. To keep more, raise ${option[kind]} in indicator(), e.g. indicator(\"...\", { ${option[kind]}: 500 }).`\n );\n }\n return out;\n}\n\n/**\n * indicator(..., { pane: 'auto' }): the plots belong on the price chart when nine values in ten (all plots together) are\n * within the price range of the bars, widened by a quarter on each side (plots with display 'none' do not count); a script\n * without plots goes on the price chart.\n */\nfunction plotsOnPrices(c: Collector): boolean {\n const b = ctxBars.bars;\n let lo = Infinity;\n let hi = -Infinity;\n for (const bar of b) {\n if (bar.low < lo) lo = bar.low;\n if (bar.high > hi) hi = bar.high;\n }\n if (!(hi >= lo)) return true;\n const margin = (hi - lo) * 0.25;\n let inside = 0;\n let total = 0;\n // the plots shown on the chart only (display 'none': values for alerts or other scripts)\n const shown = c.plotConfig.filter((p) => p.display !== 'none').map((p) => c.plots[p.id] ?? []);\n for (const points of shown) {\n for (const p of points) {\n total++;\n if (p.value >= lo - margin && p.value <= hi + margin) inside++;\n }\n }\n return total === 0 || inside >= total * 0.9;\n}\n\n// \u2500\u2500 Host entry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** What the host passes to its strategy engine factory when the script declares strategy(). */\nexport interface StrategySetup {\n properties: StrategyProperties;\n bars: readonly Bar[];\n chart: Readonly<ChartContext>;\n}\n\nexport interface ScriptOptions {\n /** Creates the order engine of a strategy script; called by strategy(). */\n strategyEngine?: (setup: StrategySetup) => StrategyEngine;\n /**\n * Records the strategy engine's answers of each bar and the `varip` values, for the intrabar runs of a strategy\n * (see {@link executeIntrabar}). The host keeps one recorder for the main run of a backtest and its intrabar runs.\n */\n recorder?: StrategyRecorder;\n /**\n * Strict mode: mistakes that PineScript lets pass silently throw a {@link ScriptError} with a plain message: an input\n * value of the wrong type, out of its range or not one of its options, an input name the script does not declare,\n * an unknown option of plot() / hline() / plotshape() / plotchar() / bgcolor() / barcolor(), a text that is not a\n * colour. Default false (PineScript behaviour); {@link defineIndicator} turns it on.\n */\n strict?: boolean;\n /**\n * Colours of the plots that give none: true for {@link DEFAULT_PALETTE} (each plot without a colour takes the next\n * one), or a list of colours. Default false: every plot without a colour is blue, as in PineScript.\n */\n palette?: boolean | readonly string[];\n /**\n * The ids of the plots in `plotConfig` and `result.plots`: 'index' (default, as PineScript numbers them: plot0,\n * plot1...) or 'title' (made from the title as the inputs' ids are: \"Fast MA\" gives fast_ma), which stay the same when\n * plots are added or moved.\n */\n plotIds?: 'index' | 'title';\n}\n\n/** The colours given in turn to plots without a colour when `ScriptOptions.palette` is true. */\nexport const DEFAULT_PALETTE: readonly string[] = ['#2962FF', '#FF6D00', '#00897B', '#AB47BC', '#F23645', '#43A047', '#FBC02D', '#8D6E63'];\n\n/** A mistake found in strict mode (see `ScriptOptions.strict`): the message says what to change. */\nexport class ScriptError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ScriptError';\n }\n}\n\nlet scriptOptions: ScriptOptions = {};\n\n/** The `varip` values of a replayed bar in a script without `varip`. */\nconst NO_VARIP: unknown[] = [];\n\n/** Intrabar run of the current run (see {@link executeIntrabar}); null in a main run. */\ninterface IntrabarRun {\n /** The bar calculated inside the bar: the last bar of the run. */\n bar: number;\n /** Bar index of the chart's last bar (`last_bar_index`, `barstate.islast`, `BarContext.n`). */\n lastBarIndex: number;\n engine: StrategyEngine;\n recorder: StrategyRecorder;\n}\nlet intrabarRun: IntrabarRun | null = null;\n\n/**\n * Answers of the strategy engine recorded in the main run of a strategy, bar by bar, and its `varip` values: an\n * intrabar run replays the bars before its bar from them (see {@link executeIntrabar}). Create one per backtest and\n * pass it to the main run (`ScriptOptions.recorder`) and to every intrabar run.\n */\nexport class StrategyRecorder {\n /** Per bar: the values the engine returned to the strategy.eachBar() callback (strategy.*, trades...), in order. */\n readonly answers: unknown[][] = [];\n /** Per bar: the `varip` values when the bar's strategy.eachBar() callback started in the main run. */\n readonly varipStarts: unknown[][] = [];\n /** Current `varip` values: kept through the intrabar runs (no rollback). */\n readonly varip: unknown[] = [];\n /**\n * Why the intrabar runs of this recorder calculate all the bars before their bar (a feature that is not resumed,\n * or a verification difference); null while they are resumed (see {@link executeIntrabar}).\n */\n get intrabarFullRunReason(): string | null {\n return intrabarChains.get(this)?.reason ?? null;\n }\n}\n\n/** Module state of a run, saved around a nested run (an intrabar run inside the bar loop of the main run). */\ninterface RunState {\n bars: Bar[];\n ctx: Collector | null;\n chartCtx: ChartContext;\n runNow: number;\n scriptOptions: ScriptOptions;\n currentBar: number;\n missingSymbols: SymbolDataRequest[];\n sessionCache: typeof sessionCache;\n intrabarRun: IntrabarRun | null;\n varip: VaripRun;\n drawings: ReturnType<typeof saveDrawingState>;\n random: ReturnType<typeof mathCore.saveRandom>;\n}\n\nfunction saveRunState(): RunState {\n return {\n bars: ctxBars.bars,\n ctx,\n chartCtx,\n runNow,\n scriptOptions,\n currentBar,\n missingSymbols,\n sessionCache,\n intrabarRun,\n varip: varipRun,\n drawings: saveDrawingState(),\n random: mathCore.saveRandom(),\n };\n}\n\nfunction restoreRunState(st: RunState): void {\n ctxBars.setAll(st.bars);\n ctx = st.ctx;\n chartCtx = st.chartCtx;\n runNow = st.runNow;\n scriptOptions = st.scriptOptions;\n currentBar = st.currentBar;\n missingSymbols = st.missingSymbols;\n sessionCache = st.sessionCache;\n intrabarRun = st.intrabarRun;\n varipRun = st.varip;\n restoreDrawingState(st.drawings);\n mathCore.restoreRandom(st.random);\n}\n\n/**\n * Runs a script body against `bars` with the given input overrides and\n * collects everything it declared. `chart` describes the bars (chart timeframe,\n * exchange time zone, session type) for the PineScript values that depend on them. `options.strategyEngine`\n * supplies the order engine of strategy scripts. This is the host-side entry \u2014 editor\n * panels, workers and tests call it; scripts never do.\n */\nexport function executeScript(\n body: () => void,\n barsInput: Bar[],\n inputs: Record<string, unknown> = {},\n chart: ChartContext = {},\n options: ScriptOptions = {}\n): ScriptRunResult {\n return runBody(body, barsInput, inputs, chart, options, null);\n}\n\n/** executeScript(), as part of an incremental run (`inc`, see createScriptRun) or alone (null). */\nfunction runBody(\n body: () => void,\n barsInput: Bar[],\n inputs: Record<string, unknown>,\n chart: ChartContext,\n options: ScriptOptions,\n inc: incremental.ActiveRun | null\n): ScriptRunResult {\n // A run inside another one (an intrabar run of a strategy) puts the outer run back when it ends.\n const outer = ctx ? saveRunState() : null;\n // A main run with a recorder starts a new backtest: its intrabar runs start again (#206).\n if (options.recorder) intrabarChains.delete(options.recorder);\n // A plain run inside an incremental one is not part of it.\n const outerInc = inc ? incremental.beginRun(inc) : incremental.suspendRun();\n ctxBars.setAll(barsInput);\n chartCtx = { ...chart };\n runNow = chart.now ?? Date.now();\n scriptOptions = options;\n ctx = freshCollector(inputs, options.strict === true);\n intrabarRun = null;\n varipRun = { slot: 0, recorder: options.recorder ?? null, mode: 'live', scratch: null };\n currentBar = -1;\n resetDrawings();\n mathCore.resetRandom();\n missingSymbols = [];\n try {\n try {\n body();\n } catch (err) {\n // An expression of request.security runs on no bar and without the symbol's properties while its bars are not\n // given (syminfo.sector there throws): the run waits for the data, not on the error.\n if (missingSymbols.length && !(err instanceof MissingSymbolDataError)) throw new MissingSymbolDataError(missingSymbols);\n throw err;\n }\n if (missingSymbols.length) throw new MissingSymbolDataError(missingSymbols);\n if (ctx.strict) checkInputNames(ctx, inputs);\n if (ctx.paneAuto) ctx.overlay = plotsOnPrices(ctx);\n // the outputs read the drawings: not a drawing of the script\n if (inc) incremental.bodyDone();\n const c = ctx;\n return {\n metadata: {\n title: c.title,\n shortTitle: c.shortTitle,\n overlay: c.overlay,\n precision: c.precision,\n format: c.format,\n ...(c.scale ? { scale: c.scale } : {}),\n ...(c.pane ? { pane: c.pane } : {}),\n },\n inputConfig: c.inputConfig,\n plotConfig: c.plotConfig,\n hlineConfig: c.hlineConfig,\n fillConfig: c.fillConfig,\n shapeConfig: c.shapeConfig,\n arrowConfig: c.arrowConfig,\n barColorConfig: c.barColorConfig,\n candleConfig: c.candleConfig,\n drawingKinds: createdDrawingKinds(),\n outputs: c.outputs,\n defaultInputs: c.defaultInputs,\n alertConfig: c.alertConfig,\n strategyConfig: c.strategy?.properties,\n result: {\n metadata: { title: c.title, shorttitle: c.shortTitle, overlay: c.overlay, precision: c.precision },\n plots: c.plots,\n fills: c.fills.length ? c.fills : undefined,\n markers: c.markers.length ? c.markers : undefined,\n outputValues: Object.keys(c.outputValues).length ? c.outputValues : undefined,\n arrows: c.arrows.length ? c.arrows : undefined,\n bgColors: c.bgColors.length ? c.bgColors : undefined,\n barColors: c.barColors.length ? c.barColors : undefined,\n plotCandles: Object.keys(c.plotCandles).length ? c.plotCandles : undefined,\n plotBars: Object.keys(c.plotBars).length ? c.plotBars : undefined,\n ...(intrabarRun ? {} : drawingOutputs(ctxBars.bars, chartCtx.timeUnit)),\n alerts: c.alerts.length ? c.alerts : undefined,\n alertCalls: c.alertCalls.length ? c.alertCalls : undefined,\n // By bar, in call order on each bar (the top-level calls make theirs on every bar at once).\n logs: c.logs.length ? [...c.logs].sort((x, y) => x.bar - y.bar).slice(-MAX_LOG_ENTRIES) : undefined,\n },\n hasAlertFunction: c.hasAlertFunction,\n usesVisibleRange: c.usesVisibleRange,\n warnings: runWarnings(),\n };\n } finally {\n ctx = null;\n if (outer) restoreRunState(outer);\n incremental.endRun(outerInc);\n }\n}\n\n/** What {@link executeIntrabar} needs besides the script. */\nexport interface IntrabarOptions {\n /** The bar calculated inside the bar: `bars` ends with it, as it stands at the tick (close = the tick price). */\n bar: number;\n /** Bar index of the chart's last bar (the main run's last bar). */\n lastBarIndex: number;\n /** The strategy engine of the main run: the order calls and `strategy.*` reads of bar `bar` go to it. */\n engine: StrategyEngine;\n /** The recorder of the main run. */\n recorder: StrategyRecorder;\n /**\n * Resume the run from the state at the start of the bar (default true, #206); false calculates all the bars before\n * it, as before.\n */\n resume?: boolean;\n /**\n * Resumed runs also calculated in full and compared, the first ones of a backtest (default 2): a difference makes the\n * next intrabar runs full ones (a script that keeps state outside persist() boxes).\n */\n verify?: number;\n}\n\n/** What {@link executeIntrabar} calculated. */\nexport interface IntrabarUpdate {\n /** First bar calculated: 0 for a full run, else the bar of the previous intrabar run (#206) */\n from: number;\n /** The run was resumed from the state of the bar before `from` */\n incremental: boolean;\n /** Why the intrabar runs of the backtest are full runs (null: resumed) */\n fullRunReason: string | null;\n}\n\n/** The intrabar runs of a backtest (one recorder): each one resumes from the state the previous one kept (#206). */\ninterface IntrabarChain {\n body: () => void;\n inputs: Record<string, unknown>;\n chart: ChartContext;\n engine: StrategyEngine;\n lastBarIndex: number;\n /** State kept by the last run (null: the next run is a full one that records it) */\n memory: incremental.RunMemory | null;\n /** Bars of the last run */\n n: number;\n reason: string | null;\n verifyLeft: number;\n}\nconst intrabarChains = new WeakMap<StrategyRecorder, IntrabarChain>();\n\n/**\n * The live engine of an intrabar run with its calls logged (`log`, to compare two runs) and its order calls, when\n * `writes` is given, kept there instead of made (a resumed run gives them to the engine once it has ended: a run\n * stopped in the middle makes none).\n */\nfunction intrabarEngine(engine: StrategyEngine, log: unknown[] | null, writes: Array<() => void> | null): StrategyEngine {\n const read = <T>(name: string, args: unknown[], value: T): T => {\n log?.push([name, ...args, value]);\n return value;\n };\n const write = (name: string, args: unknown[], call: () => void): void => {\n log?.push([name, ...args]);\n if (writes) writes.push(call);\n else call();\n };\n return {\n ...forward(engine),\n entry: (id, direction, options) => write('entry', [id, direction, options], () => engine.entry(id, direction, options)),\n order: (id, direction, options) => write('order', [id, direction, options], () => engine.order(id, direction, options)),\n exit: (id, options) => write('exit', [id, options], () => engine.exit(id, options)),\n close: (id, options) => write('close', [id, options], () => engine.close(id, options)),\n close_all: (options) => write('close_all', [options], () => engine.close_all(options)),\n cancel: (id) => write('cancel', [id], () => engine.cancel(id)),\n cancel_all: () => write('cancel_all', [], () => engine.cancel_all()),\n get: (name) => read('get', [name], engine.get(name)),\n openTrade: (index) => read('openTrade', [index], engine.openTrade(index)),\n closedTrade: (index) => read('closedTrade', [index], engine.closedTrade(index)),\n defaultEntryQty: engine.defaultEntryQty\n ? (price) => read('defaultEntryQty', [price], engine.defaultEntryQty!(price))\n : undefined,\n };\n}\n\n/** Puts the `varip` values back to a copy taken before a run. */\nfunction setVarip(recorder: StrategyRecorder, values: unknown[]): void {\n recorder.varip.length = 0;\n recorder.varip.push(...values);\n}\n\n/**\n * Host-side: runs a strategy once more on one bar, inside the bar (calculation on order fills, or on the ticks of\n * history bars). Scripts never call it. `bars` holds the bars up to that bar, the last one as it stands at the tick\n * (its close is the tick price, its high and low the extremes reached so far). The script's variables come back to\n * their state at the start of the bar, except `varip` ones. In strategy.eachBar(), the bars before replay the engine's\n * answers that the main run recorded (their order calls are dropped), and the bar itself calls `options.engine`\n * without processBar / processClose (the host is filling its orders). That bar is a confirmed history bar\n * (`barstate.isconfirmed`); `barstate.islast`, `last_bar_index` and `BarContext.n` keep the chart's last bar. Risk\n * rules are not declared again, and the outputs (plots, drawings) are dropped. Re-entrant: the host calls it inside\n * the bar loop of the main run.\n *\n * Resumed runs: the intrabar runs of a backtest (same recorder, script, inputs, chart and engine) keep the state of\n * the script as createScriptRun does, so a run calculates its bar only (and the bars since the previous intrabar run);\n * the order calls and `strategy.*` reads are the same as in a full run. The bars before `options.bar` must be the main\n * run's (the same on every call). A script that keeps state outside `persist()` boxes, or uses a feature that is not\n * resumed, gets full runs (`fullRunReason`); the first resumed runs are also calculated in full and compared\n * (`verify`). A resumed run gives its order calls to the engine once it has ended.\n * @param body - The script body, as given to executeScript().\n * @param bars - The bars up to and including the bar calculated inside, oldest first.\n * @param inputs - Input values by input id, as given to the main run.\n * @param chart - The chart context of the main run.\n * @param options - The bar, the chart's last bar index, the main run's engine and recorder, and the resume settings.\n * @returns The first bar calculated, whether the run was resumed, and why the runs are full ones (or null).\n */\nexport function executeIntrabar(\n body: () => void,\n bars: Bar[],\n inputs: Record<string, unknown>,\n chart: ChartContext,\n options: IntrabarOptions\n): IntrabarUpdate {\n const recorder = options.recorder;\n // History bars are confirmed, also on their ticks (the reference app: a barstate.isconfirmed entry fills on them).\n const runChart: ChartContext = { ...chart, lastBarConfirmed: true, realtime: false };\n const execute = (engine: StrategyEngine, inc: incremental.ActiveRun | null): void => {\n const run: IntrabarRun = { bar: options.bar, lastBarIndex: options.lastBarIndex, engine, recorder };\n runBody(\n () => {\n intrabarRun = run;\n varipRun = { slot: 0, recorder, mode: 'live', scratch: null };\n body();\n },\n bars,\n inputs,\n runChart,\n { strategyEngine: () => engine },\n inc\n );\n };\n const fullRun = (reason: string | null): IntrabarUpdate => {\n execute(options.engine, null);\n return { from: 0, incremental: false, fullRunReason: reason };\n };\n if (options.resume === false) return fullRun('resume: false');\n const n = bars.length;\n if (options.bar !== n - 1) return fullRun('the bar is not the last of the bars');\n\n let chain = intrabarChains.get(recorder);\n if (\n !chain || chain.body !== body || chain.engine !== options.engine || chain.lastBarIndex !== options.lastBarIndex ||\n !sameResult(chain.inputs, inputs) || !sameChart(chain.chart, runChart)\n ) {\n chain = {\n body,\n inputs,\n chart: runChart,\n engine: options.engine,\n lastBarIndex: options.lastBarIndex,\n memory: null,\n n: 0,\n reason: null,\n verifyLeft: options.verify ?? 2,\n };\n intrabarChains.set(recorder, chain);\n }\n if (chain.reason) return fullRun(chain.reason);\n\n const memory = chain.memory;\n // A resumed run changes the memory in place: it is usable again only when the run has ended.\n chain.memory = null;\n if (!memory || n < chain.n) {\n const inc = newActiveRun('record', bars, 0, null);\n execute(options.engine, inc);\n if (inc.blocked) chain.reason = inc.blocked;\n else {\n chain.memory = inc.next;\n chain.n = n;\n }\n return { from: 0, incremental: false, fullRunReason: chain.reason };\n }\n\n const from = chain.n - 1;\n const start = incremental.plainCopy(recorder.varip);\n if (start === incremental.NOT_COPIED) {\n chain.reason = 'a varip value that is not plain data';\n return fullRun(chain.reason);\n }\n const verifying = chain.verifyLeft > 0;\n const log: unknown[] | null = verifying ? [] : null;\n const writes: Array<() => void> = [];\n const inc = newActiveRun('resume', bars, from, memory);\n try {\n execute(intrabarEngine(options.engine, log, writes), inc);\n } catch (err) {\n // The run is calculated in full instead: the varip values back to the start, the kept order calls dropped. An\n // error of the script is the full run's (it throws it again).\n setVarip(recorder, start as unknown[]);\n if (err instanceof incremental.ResumeAborted) chain.reason = err.reason;\n return fullRun(chain.reason);\n }\n if (verifying) {\n chain.verifyLeft--;\n const resumedVarip = incremental.plainCopy(recorder.varip);\n setVarip(recorder, start as unknown[]);\n const fullLog: unknown[] = [];\n execute(intrabarEngine(options.engine, fullLog, null), null);\n if (resumedVarip === incremental.NOT_COPIED || !sameResult(log, fullLog) || !sameResult(resumedVarip, recorder.varip)) {\n chain.reason = 'a resumed intrabar run differs from a full run (state kept outside persist()?)';\n return { from: 0, incremental: false, fullRunReason: chain.reason };\n }\n } else {\n for (const call of writes) call();\n }\n chain.memory = inc.next;\n chain.n = n;\n return { from, incremental: true, fullRunReason: null };\n}\n\n/** The state of an incremental run: a recorded one (full), or one resumed at bar `from` from `prev`. */\nfunction newActiveRun(\n mode: 'record' | 'resume',\n b: Bar[],\n from: number,\n prev: incremental.RunMemory | null\n): incremental.ActiveRun {\n const next = incremental.emptyMemory(b.length);\n // the block that draws stays the one of the previous run (the forming bar may not draw)\n if (mode === 'resume' && prev) next.drawingBlock = prev.drawingBlock;\n return {\n mode,\n from,\n bars: b,\n prev: mode === 'resume' ? prev : null,\n next,\n seriesSlot: 0,\n taSlot: 0,\n blockSlot: 0,\n plotSlot: 0,\n boxSlot: 0,\n drawSlot: 0,\n block: -1,\n boxes: [],\n blocked: null,\n };\n}\n\n// \u2500\u2500 Incremental runs (#196) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The result of {@link ScriptRun.update}. */\nexport interface ScriptRunUpdate extends ScriptRunResult {\n /** First bar calculated: the forming bar of the previous update (a resumed run), or 0 (a full run) */\n from: number;\n /** The update was resumed from the state of the last confirmed bar */\n incremental: boolean;\n}\n\nexport interface ScriptRunOptions extends ScriptOptions {\n /**\n * Resumed updates also calculated in full and compared, the first ones of the run (default 2): a difference makes\n * the next updates full runs (a script that keeps state outside persist() boxes)\n */\n verify?: number;\n}\n\n/** A script calculated again on each update of the chart bars (see {@link createScriptRun}). */\nexport interface ScriptRun {\n /**\n * The script on `bars`: resumed from the forming bar of the previous update when the bars before it did not change\n * (a live update of the forming bar, or new bars after it), else a full run.\n */\n update(bars: Bar[], chart?: ChartContext): ScriptRunUpdate;\n /** Why the updates are full runs: a feature that is not resumed, or a verification difference (null: resumed) */\n readonly fullRunReason: string | null;\n}\n\n/** Chart context fields that only change the last bar (barstate of the forming bar). */\nconst LAST_BAR_FIELDS = new Set(['lastBarConfirmed', 'lastBarNew', 'realtime', 'now']);\n\n/** The visible range of the chart: part of the chart only for a script that reads it. */\nconst VISIBLE_RANGE_FIELDS = new Set(['leftVisibleBarTime', 'rightVisibleBarTime']);\n\nfunction sameChart(a: ChartContext, b: ChartContext, visibleRange = true): boolean {\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]);\n for (const k of keys) {\n if (LAST_BAR_FIELDS.has(k) || (!visibleRange && VISIBLE_RANGE_FIELDS.has(k))) continue;\n if (!Object.is((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) return false;\n }\n return true;\n}\n\n/** The bar values an update compares with the next one. */\ninterface BarsCopy {\n n: number;\n values: Float64Array;\n}\n\n/** `b` in `copy` from bar `from` on (the bars before are already there); a new copy when `copy` is null. */\nfunction copyBars(b: readonly Bar[], copy: BarsCopy | null = null, from = 0): BarsCopy {\n let values = copy?.values ?? new Float64Array(Math.max(16, b.length) * 6);\n if (values.length < b.length * 6) {\n const grown = new Float64Array(b.length * 12);\n grown.set(values.subarray(0, from * 6));\n values = grown;\n }\n for (let i = from; i < b.length; i++) {\n const x = b[i]!;\n const o = i * 6;\n values[o] = x.time as number;\n values[o + 1] = x.open;\n values[o + 2] = x.high;\n values[o + 3] = x.low;\n values[o + 4] = x.close;\n values[o + 5] = x.volume ?? NaN;\n }\n return { n: b.length, values };\n}\n\n/** a and b are the same number (NaN equal to NaN, -0 not 0) */\nconst sameNumber = (a: number, b: number): boolean => a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;\n\n/** The first `count` bars of `b` have the values of `copy`. */\nfunction sameBars(copy: BarsCopy, b: readonly Bar[], count: number): boolean {\n const v = copy.values;\n for (let i = 0; i < count; i++) {\n const x = b[i]!;\n const o = i * 6;\n if (\n !sameNumber(v[o]!, x.time as number) || !sameNumber(v[o + 1]!, x.open) || !sameNumber(v[o + 2]!, x.high) ||\n !sameNumber(v[o + 3]!, x.low) || !sameNumber(v[o + 4]!, x.close) || !sameNumber(v[o + 5]!, x.volume ?? NaN)\n ) {\n return false;\n }\n }\n return true;\n}\n\n/** Two run results with the same values (numbers compared with Object.is: NaN equal, -0 not 0). */\nfunction sameResult(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const ka = Object.keys(a);\n const kb = Object.keys(b);\n if (ka.length !== kb.length) return false;\n for (const k of ka) {\n if (!sameResult((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) return false;\n }\n return true;\n}\n\n/**\n * Host-side: a script that calculates only the newest bars on a live update. Scripts never call it. The first\n * update is a full run; it keeps,\n * for the next one, what the script created (its Series, ta.* calls, eachBar() blocks, persist() boxes and plots) with\n * their state at the end of the last confirmed bar. An update whose bars are the same up to the forming bar of the\n * previous update (a new price of the forming bar, or new bars after it) runs the script again from that bar only;\n * the result is the same as a full run on the same bars. Other changes (history loaded, inputs, symbol, timeframe or\n * other chart fields) run it in full.\n *\n * The state the script keeps from one bar to the next has to be in `persist()` boxes (not in `let` variables outside the\n * eachBar() callbacks, which a resumed run cannot put back). The first resumed updates are also calculated in full and\n * compared (`verify`): a difference makes the next updates full runs. Not resumed yet, so calculated in full: drawings,\n * request.security, strategies, varip, timenow, last_bar_index, BarContext.n, barstate.islastconfirmedhistory\n * (`fullRunReason` names the first one met).\n * @param body - The script body, a function that runs the script's statements.\n * @param inputs - Input values by input id. Default: `{}` (every input at its default).\n * @param chart - The chart context (timeframe, time zone, session, symbol...); an update can give a new one.\n * Default: `{}`.\n * @param options - The executeScript() options, plus `verify` (resumed updates also run in full and compared).\n * Default: `{}`.\n * @returns A run: call `update(bars, chart?)` on each change of the bars; `fullRunReason` says why it does not resume.\n */\nexport function createScriptRun(\n body: () => void,\n inputs: Record<string, unknown> = {},\n chart: ChartContext = {},\n options: ScriptRunOptions = {}\n): ScriptRun {\n let memory: incremental.RunMemory | null = null;\n let previous: BarsCopy | null = null;\n let previousChart: ChartContext = chart;\n let reason: string | null = null;\n let verifyLeft = options.verify ?? 2;\n /** A bar calculated so far read the visible range. */\n let rangeRead = false;\n /** The log messages of the last update: a resumed update keeps those of the bars it does not calculate again. */\n let lastLogs: LogEntry[] | undefined;\n\n const newRun = (mode: 'record' | 'resume', b: Bar[], from: number): incremental.ActiveRun =>\n newActiveRun(mode, b, from, memory);\n\n const full = (b: Bar[], c: ChartContext): ScriptRunUpdate => {\n memory = null;\n if (reason) return { ...runBody(body, b, inputs, c, options, null), from: 0, incremental: false };\n const inc = newRun('record', b, 0);\n const result = runBody(body, b, inputs, c, options, inc);\n if (inc.blocked) reason = inc.blocked;\n else memory = inc.next;\n return { ...result, from: 0, incremental: false };\n };\n\n return {\n get fullRunReason() {\n return reason;\n },\n update(b: Bar[], c: ChartContext = previousChart): ScriptRunUpdate {\n const last = previous;\n const m = memory;\n const resumable =\n !reason && m !== null && last !== null && last.n >= 1 && b.length >= last.n && sameChart(previousChart, c, rangeRead) &&\n sameBars(last, b, last.n - 1);\n previousChart = c;\n let out: ScriptRunUpdate;\n if (!resumable) {\n out = full(b, c);\n } else {\n const from = last!.n - 1;\n const inc = newRun('resume', b, from);\n let result: ScriptRunResult | null = null;\n try {\n result = runBody(body, b, inputs, c, options, inc);\n result.result.logs = resumedLogs(lastLogs, result.result.logs, from);\n result.usesVisibleRange ||= rangeRead;\n } catch (err) {\n // the memory is changed in place by a resumed run: an error leaves it unusable\n memory = null;\n previous = null;\n if (!(err instanceof incremental.ResumeAborted)) throw err;\n reason = err.reason;\n }\n if (result && verifyLeft > 0) {\n verifyLeft--;\n const check = runBody(body, b, inputs, c, options, null);\n check.usesVisibleRange = result.usesVisibleRange;\n if (!sameResult(result, check)) {\n reason = 'a resumed update differs from a full run (state kept outside persist()?)';\n result = check;\n }\n }\n if (result && !reason) {\n memory = inc.next;\n out = { ...result, from, incremental: true };\n } else {\n out = result && reason ? { ...result, from: 0, incremental: false } : full(b, c);\n memory = null;\n }\n }\n previous = out.incremental && last ? copyBars(b, last, last.n - 1) : copyBars(b);\n lastLogs = out.result.logs;\n rangeRead = out.usesVisibleRange;\n return out;\n },\n };\n}\n\n// \u2500\u2500 varip \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** How `varip` boxes read and write in the running code. */\ninterface VaripRun {\n /** Next slot (boxes are numbered in their call order in the script). */\n slot: number;\n recorder: StrategyRecorder | null;\n /** live: the recorder's current values; replay: the copy of a replayed bar's start values. */\n mode: 'live' | 'replay';\n scratch: unknown[] | null;\n}\nlet varipRun: VaripRun = { slot: 0, recorder: null, mode: 'live', scratch: null };\n\n/** A `varip` variable: `.value` reads and writes it. */\nexport interface VaripVariable<T> {\n /** The current value of the variable. */\n value: T;\n}\n\n/**\n * A strategy variable that keeps the changes made while a bar is calculated again inside the bar (on order fills or\n * ticks). A plain variable comes back to its value at the start of the bar on each of those runs; a `varip` one does\n * not, so it can count fills or ticks. Declare it once in the script body (outside the callbacks), in the same order\n * on each run; read and write `.value` in strategy.eachBar(). Without intrabar runs it is a plain variable.\n * @param initial - The starting value.\n * @returns A box whose `.value` reads and writes the variable.\n * @example\n * ```js\n * const updatesInTrade = varip(0);\n * strategy.eachBar((c) => {\n * if (strategy.position_size !== 0) updatesInTrade.value += 1;\n * });\n * ```\n */\nexport function varip<T>(initial: T): VaripVariable<T> {\n collector();\n // the intrabar runs of a backtest resume with varip values read in strategy.eachBar() (#206)\n if (!intrabarRun) incremental.nonIncremental('varip');\n const slot = varipRun.slot++;\n const state = varipRun;\n const rec = state.recorder;\n if (!rec) {\n let current = initial;\n return {\n get value() {\n return current;\n },\n set value(v: T) {\n current = v;\n },\n };\n }\n if (rec.varip.length <= slot) rec.varip[slot] = initial;\n const store = (): unknown[] => {\n // elsewhere, a resumed run would keep values of the bars before calculated with older varip values\n if (incremental.active && !ctx?.strategy?.inLoop) incremental.nonIncremental('varip used outside strategy.eachBar()');\n return state.mode === 'replay' && state.scratch ? state.scratch : rec.varip;\n };\n return {\n get value() {\n return store()[slot] as T;\n },\n set value(v: T) {\n store()[slot] = v;\n },\n };\n}\n\n// \u2500\u2500 persist \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** A `persist` variable: `.value` reads and writes it. */\nexport interface PersistVariable<T> {\n /** The current value of the variable. */\n value: T;\n}\n\n/**\n * A variable that keeps its value from one bar to the next, kept by the runtime. Declare it in the script body\n * (outside the callbacks), in the same order on each run, and read and write `.value` in one eachBar() callback. On a\n * live chart the runtime saves its value at the end of the last confirmed bar and puts it back before the forming bar\n * is calculated again, so only the newest bar is calculated: prefer it to a `let` variable outside the callback.\n * The script is calculated in full on each update (same results, slower) when the variable is used outside an\n * eachBar() callback, by two eachBar() blocks, or holds something else than plain data (numbers, strings, booleans,\n * arrays, plain objects, Map, Set). Calling it inside a bar loop throws.\n * @param initial - The value before the first bar.\n * @returns A box whose `.value` reads and writes the variable.\n * @example\n * ```js\n * const dir = persist(0);\n * const trend = eachBar((c) => {\n * if (c.close > c.get(close, 1)) dir.value = 1;\n * else if (c.close < c.get(close, 1)) dir.value = -1;\n * return dir.value;\n * });\n * ```\n */\nexport function persist<T>(initial: T): PersistVariable<T> {\n collector();\n if (currentBar >= 0) {\n throw new Error('persist() is declared in the script body, outside the eachBar() callback (once per run).');\n }\n let current = initial;\n const run = incremental.active;\n if (!run) {\n return {\n get value() {\n return current;\n },\n set value(v: T) {\n current = v;\n },\n };\n }\n const slot = run.boxSlot++;\n run.boxes[slot] = {\n get: () => current,\n set: (v) => {\n current = v as T;\n },\n };\n if (run.mode === 'resume') run.next.boxOwner[slot] = run.prev?.boxOwner[slot];\n const touch = (): void => {\n if (incremental.active !== run) return;\n if (run.block < 0) {\n incremental.nonIncremental('persist() used outside eachBar()');\n return;\n }\n const owner = run.next.boxOwner[slot];\n if (owner === undefined) run.next.boxOwner[slot] = run.block;\n else if (owner !== run.block) incremental.nonIncremental('persist() used by two eachBar() blocks');\n };\n return {\n get value() {\n touch();\n return current;\n },\n set value(v: T) {\n touch();\n current = v;\n },\n };\n}\n\n// \u2500\u2500 Declarations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Options of {@link indicator}. */\nexport interface IndicatorOptions {\n /** Short name shown in the chart legend. Default: the title. */\n shorttitle?: string;\n /** true: drawn on the price pane; false: in its own pane below the chart. Default: false. */\n overlay?: boolean;\n /** Number of decimals of the values shown in the legend and on the price scale. Default: the host's choice (the symbol's precision). */\n precision?: number;\n /** Number format of the values: `format.price`, `format.volume`, `format.percent`, `format.mintick` or `format.inherit`. Default: `format.inherit`. */\n format?: string;\n /** The price scale the script uses: `scale.right`, `scale.left` or `scale.none`. Default: the host's choice. */\n scale?: 'right' | 'left' | 'none';\n /** Most lines kept alive; above it the oldest are deleted (a few more may stay for a moment). Default: 50. */\n max_lines_count?: number;\n /** Most labels kept alive; above it the oldest are deleted. Default: 50. */\n max_labels_count?: number;\n /** Most boxes kept alive; above it the oldest are deleted. Default: 50. */\n max_boxes_count?: number;\n /** Most polylines kept alive; above it the oldest are deleted. Default: 50. */\n max_polylines_count?: number;\n /**\n * Where the script is drawn, instead of `overlay` (give one of the two): 'price' (on the price pane), 'separate'\n * (its own pane) or 'auto' (chosen from the plotted values: the price pane when they are prices, like an average;\n * its own pane otherwise, like an RSI). Default: not set (`overlay` decides).\n */\n pane?: 'price' | 'separate' | 'auto';\n}\n\n/**\n * Declares the script as an indicator: its title, its pane and how its values are shown. Call it once, at the top\n * of the script (a script declares either `indicator()` or `strategy()`). A script without a declaration runs with\n * the title \"Untitled\" in its own pane.\n * @param title - Name of the script, shown in the legend and the settings.\n * @param options - Pane, short title, number format and drawing limits. Default: `{}` (own pane).\n * @example\n * ```js\n * indicator(\"My SMA\", { overlay: true, precision: 2 });\n * plot(ta.sma(close, 20), \"SMA\");\n * ```\n */\nexport function indicator(title: string, options: IndicatorOptions = {}): void {\n const c = collector();\n declare(c, 'indicator');\n c.title = title;\n c.shortTitle = options.shorttitle;\n if (options.pane !== undefined) {\n if (!['price', 'separate', 'auto'].includes(options.pane)) {\n throw new ScriptError(`indicator(): pane is 'price', 'separate' or 'auto', got ${shown(options.pane)}.`);\n }\n if (options.overlay !== undefined) throw new ScriptError('indicator(): give overlay or pane, not both.');\n }\n c.overlay = options.pane === 'price' ? true : options.pane === undefined ? (options.overlay ?? false) : false;\n c.paneAuto = options.pane === 'auto';\n c.pane = options.pane;\n c.precision = options.precision;\n c.format = options.format;\n c.scale = options.scale;\n setDrawingLimits({\n line: options.max_lines_count,\n label: options.max_labels_count,\n box: options.max_boxes_count,\n polyline: options.max_polylines_count,\n });\n}\n\nfunction declare(c: Collector, kind: 'indicator' | 'strategy'): void {\n if (c.declaration) {\n throw new Error(`${kind}(): the script already declared ${c.declaration}(); a script has one declaration.`);\n }\n c.declaration = kind;\n}\n\n/** Options of every `input.*` kind: where the input is listed in the settings and how it behaves. */\nexport interface InputOptions {\n /** Group title: every input with the same `group` is listed under it, at the place of the group's first input. Default: no group. */\n group?: string;\n /** Inputs with the same `inline` id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own. */\n inline?: string;\n /** Help text shown next to the input. Default: none. */\n tooltip?: string;\n /** true: the host asks for the value when the script is added to a chart. Default: false. */\n confirm?: boolean;\n /**\n * Where the value is shown besides the settings: `display.all`, `display.none`, `display.status_line` or\n * `display.data_window`. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.\n */\n display?: InputConfig['display'];\n /**\n * false greys the input out in the settings (it keeps its value). A boolean (`active: showMa`), or a condition on\n * input ids that a host can apply without running the script (`active: 'ma_1'`,\n * `active: { input: 'type', ne: 'None' }`). Default: true.\n */\n active?: boolean | InputCondition;\n /**\n * The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made\n * from the title (\"Fast length\" gives fast_length), which changes when the title changes.\n */\n id?: string;\n}\n\n/** Options of `input.int()` and `input.float()`. */\nexport interface NumericInputOptions extends InputOptions {\n /** Smallest value the user can enter. Default: no minimum. */\n minval?: number;\n /** Largest value the user can enter. Default: no maximum. */\n maxval?: number;\n /** Step of the arrows of the number field. Default: the host's choice (1 for an int). */\n step?: number;\n /** The values to choose from (the host shows a drop-down list). Default: a free number field. */\n options?: number[];\n}\n\n/** A field of an enum made with `defineEnum()`: its name and title. `String(field)` is the title. */\nexport interface EnumField {\n /** The field's name, as written in `defineEnum()` (`\"sma\"`). */\n readonly name: string;\n /** The field's title, shown in the settings (`\"Simple\"`); the name when the title was empty. */\n readonly title: string;\n /** The title, so `String(field)` and `str.tostring(field)` give it. */\n toString(): string;\n}\n\n/** Options of `input.enum()`. */\nexport interface EnumInputOptions extends InputOptions {\n /** The fields to choose from, all of the default's enum. Default: every field of the enum. */\n options?: EnumField[];\n}\n\n/** A class, not a plain object: a field passed where the options can be is not read as named arguments. */\nclass EnumFieldValue implements EnumField {\n constructor(readonly name: string, readonly title: string) {\n Object.freeze(this);\n }\n toString(): string {\n return this.title;\n }\n}\n\n/** The fields of each enum, by field: `input.enum()` lists them from its default. */\nconst enumFieldsOf = new WeakMap<EnumField, readonly EnumField[]>();\n\n/**\n * Makes an enum: a fixed set of named fields, each with a title, for a choice list (`input.enum()`) or a state with\n * a few values. Fields compare with `===`; `field.name` is the name, `field.title` and `String(field)` the title.\n * @param fields - An object of field names and titles, e.g. `{ sma: \"Simple\", ema: \"Exponential\" }`; an empty title\n * is the name.\n * @returns A frozen object with one {@link EnumField} per name.\n * @example\n * ```js\n * const MaType = defineEnum({ sma: \"Simple\", ema: \"Exponential\" });\n * const maType = input.enum(MaType.sma, \"Average\");\n * plot(maType === MaType.ema ? ta.ema(close, 20) : ta.sma(close, 20), \"MA\");\n * ```\n */\nexport function defineEnum<K extends string>(fields: Record<K, string>): { readonly [P in K]: EnumField } {\n if (!isPlainObject(fields) || Object.keys(fields).length === 0) {\n throw new TypeError('defineEnum(): the fields are an object of names and titles, e.g. { sma: \"Simple\", ema: \"Exponential\" }.');\n }\n const list: EnumField[] = [];\n const out: Record<string, EnumField> = {};\n for (const [name, title] of Object.entries(fields)) {\n if (title !== undefined && typeof title !== 'string') throw new TypeError(`defineEnum(): the title of \"${name}\" is a string.`);\n const field = new EnumFieldValue(name, title || name);\n list.push(field);\n out[name] = field;\n }\n for (const field of list) enumFieldsOf.set(field, list);\n return Object.freeze(out) as { readonly [P in K]: EnumField };\n}\n\n/** Options of `input.string()`, `input.timeframe()`, `input.session()` and `input.symbol()`. */\nexport interface StringInputOptions extends InputOptions {\n /** The values to choose from (the host shows a drop-down list). Default: a free text field (or the kind's own picker). */\n options?: string[];\n}\n\n/** The InputConfig fields of the common input options (unset options are left out). */\nfunction common(opts: InputOptions): Partial<InputConfig> {\n const out: Partial<InputConfig> = {};\n if (opts.group !== undefined) out.group = opts.group;\n if (opts.inline !== undefined) out.inline = opts.inline;\n if (opts.tooltip !== undefined) out.tooltip = opts.tooltip;\n if (opts.confirm !== undefined) out.confirm = opts.confirm;\n if (opts.display !== undefined) out.display = opts.display;\n if (opts.active !== undefined) out.active = opts.active;\n if (opts.id !== undefined) out.id = opts.id;\n return out;\n}\n\n/** Declares the input in the collector and returns its current value (the\n * host-supplied override when present, else the default). */\nfunction registerInput<T>(config: Omit<InputConfig, 'id'>, fallbackId: string): T {\n const c = collector();\n const wanted = (config as Partial<InputConfig>).id;\n let id: string;\n if (wanted !== undefined) {\n if (typeof wanted !== 'string' || !/^[A-Za-z_]\\w*$/.test(wanted)) {\n throw new ScriptError(`input id ${shown(wanted)}: letters, digits and _ only, not starting with a digit, e.g. \"fast_length\".`);\n }\n if (c.inputIds.has(wanted)) throw new ScriptError(`Two inputs have the id \"${wanted}\": give each its own.`);\n c.inputIds.add(wanted);\n id = wanted;\n } else {\n id = slugId(config.title, fallbackId, c.inputIds);\n }\n c.inputConfig.push({ ...config, id });\n c.defaultInputs[id] = config.defval;\n const value = c.inputValues[id];\n if (c.strict && value !== undefined) checkInputValue({ id, ...config }, id, value);\n return (value === undefined ? config.defval : value) as T;\n}\n\n/** `idKind`: the kind in the id of an input without title (a price input keeps the ids of the float input it was). */\nfunction registerNumeric(type: 'int' | 'float' | 'price', defval: number, title?: string, opts: NumericInputOptions = {}, idKind: string = type): number {\n const v = registerInput<unknown>(\n { type, defval, title, min: opts.minval, max: opts.maxval, step: opts.step, ...(opts.options ? { options: opts.options } : {}), ...common(opts) },\n `input_${idKind}`\n );\n return typeof v === 'number' ? v : defval;\n}\n\n/** Named arguments of an input: its options, with `title` (and `defval` when every argument is named). */\ntype InputArgs<O, D> = O & { title?: string; defval?: D };\n\nconst COMMON_INPUT_KEYS = ['tooltip', 'inline', 'group', 'confirm', 'display', 'active', 'id'] as const;\n/** The PineScript arguments of each input kind (named arguments are checked against them). */\nconst INPUT_KEYS: Record<string, readonly string[]> = {\n int: ['defval', 'title', 'minval', 'maxval', 'step', 'options', ...COMMON_INPUT_KEYS],\n float: ['defval', 'title', 'minval', 'maxval', 'step', 'options', ...COMMON_INPUT_KEYS],\n enum: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],\n price: ['defval', 'title', ...COMMON_INPUT_KEYS],\n bool: ['defval', 'title', ...COMMON_INPUT_KEYS],\n string: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],\n text_area: ['defval', 'title', ...COMMON_INPUT_KEYS],\n color: ['defval', 'title', ...COMMON_INPUT_KEYS],\n source: ['defval', 'title', ...COMMON_INPUT_KEYS],\n timeframe: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],\n session: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],\n symbol: ['defval', 'title', 'options', ...COMMON_INPUT_KEYS],\n time: ['defval', 'title', ...COMMON_INPUT_KEYS],\n};\n\n/**\n * The default, title and options of an `input.*` call, as PineScript writes it: `(defval, title, options)`,\n * `(defval, { title, ...options })` or every argument by name (`{ defval, title, ...options }`). An unknown named\n * argument throws with the closest names (`min` for `minval`).\n */\nfunction inputArgs<D, O extends object>(\n kind: string,\n defvalOrArgs: unknown,\n titleOrArgs: unknown,\n opts: O | undefined\n): { defval: D; title: string | undefined; opts: O } {\n const name = `input.${kind}`;\n const keys = INPUT_KEYS[kind]!;\n let named: Record<string, unknown> = {};\n let defval = defvalOrArgs;\n let title: unknown = titleOrArgs;\n if (isPlainObject(defvalOrArgs)) {\n named = { ...defvalOrArgs };\n defval = named.defval;\n title = undefined;\n } else if (isPlainObject(titleOrArgs)) {\n named = { ...titleOrArgs };\n title = undefined;\n }\n if (opts !== undefined) {\n if (!isPlainObject(opts)) throw new TypeError(`${name}(): the options are an object, e.g. { tooltip: \"...\" }.`);\n named = { ...named, ...opts };\n }\n for (const key of Object.keys(named)) if (!keys.includes(key)) throw unknownArgument(name, key, keys);\n if (title !== undefined && typeof title !== 'string') {\n throw new TypeError(`${name}(): the title is a string, got ${typeof title}.`);\n }\n const { defval: namedDefval, title: namedTitle, ...rest } = named;\n return {\n defval: (defval ?? namedDefval) as D,\n title: (title as string | undefined) ?? (namedTitle as string | undefined),\n opts: rest as O,\n };\n}\n\n/**\n * Script inputs: each `input.*` call declares a setting the user can change AND returns its current value (the\n * user's value when there is one, else the default). The arguments after the default can be named:\n * `input.int(14, \"Length\", { minval: 1 })`, `input.int(14, { title: \"Length\", minval: 1 })` or\n * `input.int({ defval: 14, title: \"Length\" })`. The input id is the title in snake case (\"Fast length\" is\n * `fast_length`); keep titles stable, a renamed input loses the user's value.\n */\nexport const input = strictNamespace('input', {\n /**\n * Declares a whole-number setting (a length, a count) and returns its value, rounded to an integer.\n * @param defval - Default value, or every argument by name (`{ defval, title, minval... }`).\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_int`).\n * @param opts - `minval`, `maxval`, `step`, `options` (a choice list) and the common input options.\n * @returns The current value: the user's value, else `defval`.\n * @example\n * ```js\n * const length = input.int(14, \"Length\", { minval: 1, maxval: 500 });\n * plot(ta.rsi(close, length), \"RSI\");\n * ```\n */\n int(defval: number | InputArgs<NumericInputOptions, number>, title?: string | InputArgs<NumericInputOptions, number>, opts?: NumericInputOptions): number {\n const a = inputArgs<number, NumericInputOptions>('int', defval, title, opts);\n return Math.round(registerNumeric('int', a.defval, a.title, a.opts));\n },\n /**\n * Declares a decimal-number setting (a multiplier, a percent, a level) and returns its value.\n * @param defval - Default value, or every argument by name (`{ defval, title, minval... }`).\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_float`).\n * @param opts - `minval`, `maxval`, `step`, `options` (a choice list) and the common input options.\n * @returns The current value: the user's value, else `defval`.\n * @example\n * ```js\n * const mult = input.float(2.0, \"Multiplier\", { minval: 0.1, step: 0.1 });\n * const [basis, upper, lower] = ta.bb(close, 20, mult);\n * ```\n */\n float(defval: number | InputArgs<NumericInputOptions, number>, title?: string | InputArgs<NumericInputOptions, number>, opts?: NumericInputOptions): number {\n const a = inputArgs<number, NumericInputOptions>('float', defval, title, opts);\n return registerNumeric('float', a.defval, a.title, a.opts);\n },\n /**\n * Declares an on / off setting (a checkbox) and returns its value. Shown only in the settings by default.\n * @param defval - Default value, or every argument by name (`{ defval, title... }`).\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_bool`).\n * @param opts - The common input options (`group`, `inline`, `tooltip`, `confirm`, `display`, `active`, `id`).\n * @returns The current value: the user's value, else `defval`.\n * @example\n * ```js\n * const showMa = input.bool(true, \"Show MA\");\n * plot(ta.sma(close, 20), \"MA\", { display: showMa ? display.all : display.none });\n * ```\n */\n bool(defval: boolean | InputArgs<InputOptions, boolean>, title?: string | InputArgs<InputOptions, boolean>, opts?: InputOptions): boolean {\n const a = inputArgs<boolean, InputOptions>('bool', defval, title, opts);\n return registerInput<boolean>({ type: 'bool', defval: a.defval, title: a.title, ...common(a.opts) }, 'input_bool');\n },\n /**\n * Declares a text setting and returns its value; with `options`, a drop-down list of choices.\n * @param defval - Default value (one of `options` when they are given), or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_string`).\n * @param opts - `options` (a choice list) and the common input options.\n * @returns The current value: the user's value, else `defval`.\n * @example\n * ```js\n * const maType = input.string(\"EMA\", \"MA type\", { options: [\"SMA\", \"EMA\"] });\n * const ma = maType === \"SMA\" ? ta.sma(close, 20) : ta.ema(close, 20);\n * ```\n */\n string(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string {\n const a = inputArgs<string, StringInputOptions>('string', defval, title, opts);\n return registerInput<string>({ type: 'string', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_string');\n },\n /**\n * Declares a multi-line text setting (lines separated by a newline) and returns its value, e.g. a list of levels\n * the script parses. Shown only in the settings by default.\n * @param defval - Default text, or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_text_area`).\n * @param opts - The common input options.\n * @returns The current text: the user's text, else `defval`.\n * @example\n * ```js\n * const text = input.text_area(\"100\\n105\\n110\", \"Levels\");\n * for (const lvl of text.split(\"\\n\")) hline(Number(lvl), \"Level \" + lvl);\n * ```\n */\n text_area(defval: string | InputArgs<InputOptions, string>, title?: string | InputArgs<InputOptions, string>, opts?: InputOptions): string {\n const a = inputArgs<string, InputOptions>('text_area', defval, title, opts);\n return registerInput<string>({ type: 'text_area', defval: a.defval, title: a.title, ...common(a.opts) }, 'input_text_area');\n },\n /**\n * Declares a colour setting (a colour picker) and returns its value. The default's transparency is kept to 2\n * decimals (`color.new(c, 90)` gives the alpha byte 26); a value given by the host is used as it is. Shown only in\n * the settings by default.\n * @param defval - Default colour (`color.blue`, `\"#2962FF\"`, `color.new(...)`), or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_color`).\n * @param opts - The common input options.\n * @returns The current colour string: the user's colour, else `defval`.\n * @example\n * ```js\n * const lineColor = input.color(color.teal, \"Line colour\");\n * plot(ta.ema(close, 20), \"EMA\", { color: lineColor });\n * ```\n */\n color(defval: string | InputArgs<InputOptions, string>, title?: string | InputArgs<InputOptions, string>, opts?: InputOptions): string {\n const a = inputArgs<string, InputOptions>('color', defval, title, opts);\n return registerInput<string>({ type: 'color', defval: inputColorDefault(a.defval), title: a.title, ...common(a.opts) }, 'input_color');\n },\n /**\n * Declares a source setting (the price a calculation reads) and returns it as a Series. The choices are `open`,\n * `high`, `low`, `close`, `volume`, `hl2`, `hlc3`, `ohlc4`, `hlcc4`, and the outputs of other scripts on the chart\n * when the host allows it (an unknown source gives `close`).\n * @param defval - Default source, by name (`\"close\"`) or as the built-in Series (`close`), or every argument by\n * name. Default: `\"close\"`.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_source`).\n * @param opts - The common input options.\n * @returns The chosen source as a Series.\n * @example\n * ```js\n * const src = input.source(close, \"Source\");\n * plot(ta.sma(src, 20), \"SMA\");\n * ```\n */\n source(defval: string | Series = 'close', title?: string | InputArgs<InputOptions, string | Series>, opts?: InputOptions): Series {\n const a = inputArgs<string | Series, InputOptions>('source', defval, title, opts);\n const name = registerInput<string>({ type: 'source', defval: sourceName(a.defval ?? 'close'), title: a.title, ...common(a.opts) }, 'input_source');\n return sourceSeries(name);\n },\n /**\n * Declares a timeframe setting (a timeframe picker) and returns its value, for `request.security()` or\n * `timeframe.change()`.\n * @param defval - Default timeframe: `\"60\"` (60 minutes), `\"D\"`, `\"W\"`, `\"M\"`...; `\"\"` is the chart's timeframe.\n * Or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_timeframe`).\n * @param opts - `options` (a choice list of timeframes) and the common input options.\n * @returns The current timeframe string (`\"\"`: the chart's timeframe).\n * @example\n * ```js\n * const tf = input.timeframe(\"D\", \"Higher timeframe\");\n * const htfClose = request.security(\"\", tf, () => close);\n * ```\n */\n timeframe(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string {\n const a = inputArgs<string, StringInputOptions>('timeframe', defval, title, opts);\n return registerInput<string>({ type: 'timeframe', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_timeframe');\n },\n /**\n * Declares a trading-hours setting and returns its value, a session string for `time()` or `inSession()`.\n * @param defval - Default session: `\"HHMM-HHMM\"`, optionally followed by `:` and the days (1 = Sunday ...\n * 7 = Saturday), e.g. `\"0930-1600\"` or `\"0930-1600:23456\"`. Or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_session`).\n * @param opts - `options` (a choice list of sessions) and the common input options.\n * @returns The current session string.\n * @example\n * ```js\n * const sess = input.session(\"0930-1600\", \"Session\");\n * bgcolor(color.when(na(time(\"\", sess)).not(), color.new(color.blue, 90)));\n * ```\n */\n session(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string {\n const a = inputArgs<string, StringInputOptions>('session', defval, title, opts);\n return registerInput<string>({ type: 'session', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_session');\n },\n /**\n * Declares a symbol setting (a symbol search) and returns its value, a ticker id for `request.security()` of\n * another symbol.\n * @param defval - Default ticker id, `\"EXCHANGE:TICKER\"` (`\"NASDAQ:MSFT\"`), or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_symbol`).\n * @param opts - `options` (a choice list of symbols) and the common input options.\n * @returns The current ticker id.\n * @example\n * ```js\n * const other = input.symbol(\"NASDAQ:MSFT\", \"Compare with\");\n * plot(request.security(other, \"\", () => close), \"Other close\");\n * ```\n */\n symbol(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string {\n const a = inputArgs<string, StringInputOptions>('symbol', defval, title, opts);\n return registerInput<string>({ type: 'symbol', defval: a.defval, title: a.title, options: a.opts.options, ...common(a.opts) }, 'input_symbol');\n },\n /**\n * Declares a price-level setting (a number field) and returns its value. With `confirm: true` the host can ask the\n * user to pick it on the chart; an `inline` id shared with an `input.time()` makes one chart point of both.\n * @param defval - Default price, or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_float`).\n * @param opts - The common input options.\n * @returns The current price: the user's value, else `defval`.\n * @example\n * ```js\n * const level = input.price(100, \"Level\", { confirm: true });\n * hline(level, \"Level\");\n * ```\n */\n price(defval: number | InputArgs<InputOptions, number>, title?: string | InputArgs<InputOptions, number>, opts?: InputOptions): number {\n const a = inputArgs<number, InputOptions>('price', defval, title, opts);\n return registerNumeric('price', a.defval, a.title, a.opts, 'float');\n },\n /**\n * Declares a choice among the fields of an enum made with `defineEnum()` and returns the chosen field. The\n * settings list the fields by title; the host stores the field's name.\n * @param defval - Default field (`MaType.sma`), or every argument by name. It must be one of `options`.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_enum`).\n * @param opts - `options` (only these fields of the enum) and the common input options.\n * @returns The chosen field; compare it with `===`.\n * @example\n * ```js\n * const MaType = defineEnum({ sma: \"Simple\", ema: \"Exponential\" });\n * const maType = input.enum(MaType.sma, \"Average\");\n * const ma = maType === MaType.ema ? ta.ema(close, 20) : ta.sma(close, 20);\n * ```\n */\n enum<F extends EnumField>(defval: F | InputArgs<EnumInputOptions, F>, title?: string | InputArgs<EnumInputOptions, F>, opts?: EnumInputOptions): F {\n const a = inputArgs<F, EnumInputOptions>('enum', defval, title, opts);\n const fields = a.defval === undefined ? undefined : enumFieldsOf.get(a.defval);\n if (!fields) throw new TypeError('input.enum(): the default is a field of an enum made with defineEnum(), e.g. input.enum(MaType.sma, \"Average\").');\n const choices = a.opts.options ?? fields;\n for (const f of choices) {\n if (!fields.includes(f)) throw new TypeError('input.enum(): the options are fields of the enum of the default.');\n }\n if (!choices.includes(a.defval)) throw new TypeError('input.enum(): the default is one of the options.');\n const name = registerInput<unknown>(\n {\n type: 'enum',\n defval: a.defval.name,\n title: a.title,\n options: choices.map((f) => f.name),\n optionsTitles: Object.fromEntries(choices.map((f) => [f.name, f.title])),\n ...common(a.opts),\n },\n 'input_enum'\n );\n return (choices.find((f) => f.name === name) ?? a.defval) as F;\n },\n /**\n * Declares a date-and-time setting and returns it as a UNIX time in milliseconds. With `confirm: true` the host\n * can ask the user to pick it on the chart. Shown only in the settings by default.\n * @param defval - Default time in ms, usually from `timestamp()`, or every argument by name.\n * @param title - Label in the settings, or the options with `title` in them. Default: none (id `input_time`).\n * @param opts - The common input options.\n * @returns The current time in ms: the user's value, else `defval`.\n * @example\n * ```js\n * const start = input.time(timestamp(\"2024-01-01\"), \"Start\");\n * bgcolor(color.when(time.gte(start), color.new(color.green, 90)));\n * ```\n */\n time(defval: number | InputArgs<InputOptions, number>, title?: string | InputArgs<InputOptions, number>, opts?: InputOptions): number {\n const a = inputArgs<number, InputOptions>('time', defval, title, opts);\n const v = registerInput<unknown>({ type: 'time', defval: a.defval, title: a.title, ...common(a.opts) }, 'input_time');\n return typeof v === 'number' ? v : a.defval;\n },\n});\n\n// \u2500\u2500 OHLCV builtins \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Opening price of each bar, as a Series. In a bar loop, `c.open` is the value of the current bar.\n * @example\n * ```js\n * const body = close.sub(open);\n * plot(body, \"Body\", { style: plot.style_columns });\n * ```\n */\nexport const open = Series.fromBars(ctxBars, 'open');\n/**\n * Highest price of each bar, as a Series. In a bar loop, `c.high` is the value of the current bar.\n * @example\n * ```js\n * plot(ta.highest(high, 20), \"20-bar high\");\n * ```\n */\nexport const high = Series.fromBars(ctxBars, 'high');\n/**\n * Lowest price of each bar, as a Series. In a bar loop, `c.low` is the value of the current bar.\n * @example\n * ```js\n * plot(ta.lowest(low, 20), \"20-bar low\");\n * ```\n */\nexport const low = Series.fromBars(ctxBars, 'low');\n/**\n * Closing price of each bar, as a Series (on the forming bar, the latest price). The usual source of indicators.\n * In a bar loop, `c.close` is the value of the current bar.\n * @example\n * ```js\n * plot(ta.sma(close, 20), \"SMA\");\n * ```\n */\nexport const close = Series.fromBars(ctxBars, 'close');\n/**\n * Traded volume of each bar, as a Series (NaN when the data has no volume). In a bar loop, `c.volume`.\n * @example\n * ```js\n * plot(volume, \"Volume\", { style: plot.style_columns });\n * ```\n */\nexport const volume = Series.fromBars(ctxBars, 'volume');\n/**\n * Median price of each bar, (high + low) / 2, as a Series.\n * @example\n * ```js\n * plot(ta.sma(hl2, 10), \"Median SMA\");\n * ```\n */\nexport const hl2 = new Series(ctxBars, (b) => (b.high + b.low) / 2);\n/**\n * Typical price of each bar, (high + low + close) / 3, as a Series.\n * @example\n * ```js\n * plot(ta.sma(hlc3, 20), \"Typical SMA\");\n * ```\n */\nexport const hlc3 = new Series(ctxBars, (b) => (b.high + b.low + b.close) / 3);\n/**\n * Average price of each bar, (open + high + low + close) / 4, as a Series.\n * @example\n * ```js\n * plot(ohlc4, \"OHLC average\");\n * ```\n */\nexport const ohlc4 = new Series(ctxBars, (b) => (b.open + b.high + b.low + b.close) / 4);\n/**\n * Weighted close of each bar, (high + low + close + close) / 4, as a Series.\n * @example\n * ```js\n * plot(ta.ema(hlcc4, 20), \"Weighted close EMA\");\n * ```\n */\nexport const hlcc4 = new Series(ctxBars, (b) => (b.high + b.low + 2 * b.close) / 4);\n/**\n * Index of each bar, as a Series: 0 on the oldest bar, then 1, 2... In a bar loop, `c.i` is the same number.\n * @example\n * ```js\n * plotshape(bar_index.mod(10).eq(0), \"Every 10 bars\", { style: shape.circle });\n * ```\n */\nexport const bar_index = new Series(ctxBars, (_b, i) => i);\nbar_index.fullHistory = true;\n/**\n * Index of the last bar of the chart, the same on every bar, as a Series. In a bar loop, `c.n - 1`.\n * @example\n * ```js\n * bgcolor(color.when(bar_index.gte(last_bar_index.sub(9)), color.new(color.blue, 90)), { title: \"Last 10 bars\" });\n * ```\n */\nexport const last_bar_index = new Series(ctxBars, (_b, _i, data) => {\n // the same value on every bar, changed by a new bar: not kept by an incremental run (#196), but the same in the\n // intrabar runs of a backtest (the chart's last bar, #206)\n if (!intrabarRun) incremental.nonIncremental('last_bar_index');\n return chartBarCount(data.length) - 1;\n});\nlast_bar_index.fullHistory = true;\n// built-in price variables keep the whole history (no 5000-bar limit)\nfor (const s of [hl2, hlc3, ohlc4, hlcc4]) s.fullHistory = true;\n\nconst SOURCES: Record<string, Series> = { open, high, low, close, volume, hl2, hlc3, ohlc4, hlcc4 };\n\n/** The name of a source default: `input.source(close)` as `input.source(\"close\")` (PineScript passes the series). */\nfunction sourceName(defval: string | Series): string {\n if (typeof defval === 'string') return defval;\n const name = Object.keys(SOURCES).find((k) => SOURCES[k] === defval);\n if (!name) {\n throw new Error('input.source(): the default must be a built-in source (open, high, low, close, volume, hl2, hlc3, ohlc4, hlcc4).');\n }\n return name;\n}\n\nfunction sourceSeries(name: string): Series {\n const builtin = SOURCES[name];\n if (builtin) return builtin;\n // Another source (study on study): its values as the host gives them now, aligned with the bars.\n const ext = externalSource(name);\n if (!ext) return close;\n const values = Array.from(ext);\n return new Series(ctxBars, (_bar, i) => values[i] ?? NaN);\n}\n\n// \u2500\u2500 Bound ta namespace \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst bars = (): Bar[] => ctxBars.bars;\n\n/** A Series bound to the context bars whose values come from one pass over all bars\n * (cumulative indicators), recomputed when the bars version changes. */\nfunction barsSeries(compute: (b: Bar[]) => Series): Series {\n let version = -1;\n let values: number[] = [];\n return new Series(ctxBars, (_bar, i, data) => {\n if (version !== ctxBars.version) {\n values = compute(data).toArray();\n version = ctxBars.version;\n }\n return values[i] ?? NaN;\n });\n}\n\n// \u2500\u2500 Guards for script mistakes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Edit distance of two names (for the \"did you mean\" of a namespace). */\nfunction editDistance(a: string, b: string): number {\n const row = Array.from({ length: b.length + 1 }, (_, j) => j);\n for (let i = 1; i <= a.length; i++) {\n let diag = row[0]!;\n row[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const up = row[j]!;\n row[j] = Math.min(up + 1, row[j - 1]! + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));\n diag = up;\n }\n }\n return row[b.length]!;\n}\n\n/** Names a tool reads to probe an object (promise, JSON, test matchers, module interop): never an error. */\nconst PROBED_NAMES = new Set(['then', 'toJSON', 'asymmetricMatch', 'nodeType', 'tagName', 'inspect', 'default']);\n\n/**\n * Compile-time check that a namespace's documented interface lists exactly the members of its implementation: a\n * member added to one but not the other makes the call fail to type-check (the argument becomes `false`).\n */\nfunction sameKeys<A, B>(_same: [Exclude<keyof A, keyof B>, Exclude<keyof B, keyof A>] extends [never, never] ? true : false): void {}\n\n/**\n * A namespace whose unknown members throw instead of being `undefined`: `ta.smaa(close, 5)` fails with\n * \"ta.smaa does not exist. Did you mean ta.sma?\" rather than \"ta.smaa is not a function\", and `color.purpel`\n * fails where it is read rather than giving a plot with no colour.\n */\nfunction strictNamespace<T extends object>(name: string, members: T): T {\n return new Proxy(members, {\n get(target, prop, receiver) {\n if (typeof prop === 'symbol' || prop in target || PROBED_NAMES.has(prop) || /^[_$@]/.test(prop)) {\n return Reflect.get(target, prop, receiver);\n }\n const keys = Object.keys(target);\n const lower = prop.toLowerCase();\n const ranked = keys\n .map((k) => ({ k, d: editDistance(lower, k.toLowerCase()) }))\n .filter(({ k, d }) => {\n const key = k.toLowerCase();\n return d <= Math.max(1, Math.floor(prop.length / 3)) || key.includes(lower) || (key.length >= 3 && lower.includes(key));\n })\n .sort((x, y) => x.d - y.d)\n .slice(0, 3)\n .map(({ k }) => `${name}.${k}`);\n throw new TypeError(\n `${name}.${prop} does not exist.` + (ranked.length ? ` Did you mean ${ranked.join(', ')}?` : '') +\n ' See docs/inventory.md for the supported functions.'\n );\n },\n });\n}\n\n/**\n * The ta.* functions compute a whole Series in one call. Called inside an eachBar() callback, a call runs again on\n * every bar (slow) and returns a Series, not the value of the bar, and it has no per-bar history: the call throws\n * with the fix.\n */\nfunction outsideBarLoops<T extends Record<string, unknown>>(members: T, ns = 'ta'): T {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(members)) {\n if (typeof value !== 'function') {\n out[key] = value;\n continue;\n }\n const fn = value as (...args: unknown[]) => unknown;\n out[key] = function (this: unknown, ...args: unknown[]) {\n if (currentBar >= 0) {\n throw new Error(\n `${ns}.${key}() was called inside eachBar(): a ${ns}.* call computes the whole Series at once. ` +\n `Compute it before the loop (const x = ${ns}.${key}(...)) and read the bar's value with c.get(x). ` +\n 'For a Pine ta.* call inside an if block or a for loop, use the callsite.* call sites.'\n );\n }\n return fn.apply(this, args);\n };\n }\n return out as T;\n}\n\n/**\n * A ta.* call of the script that has a {@link taStep} machine (#196). Outside an incremental run, the array function\n * (`full`). In an incremental run, the machine steps every bar of a recorded run, and only the bars from the forming bar\n * of the previous run in a resumed one (the machine holds the state of the last confirmed bar): the same doubles\n * (tests/ta/step.test.ts).\n */\nfunction stepped<R>(\n kind: string,\n make: () => BarStep<never[], unknown>,\n sources: Series[],\n args: (values: number[][], i: number) => unknown[],\n outs: number,\n full: () => R\n): R {\n const run = incremental.active;\n if (!run) return full();\n const slot = run.taSlot++;\n const b = sources[0] ? (sources[0].bars as Bar[]) : bars();\n const n = b.length;\n const values = sources.map((s) => s.toArray());\n let mem: incremental.TaMemory;\n let from = 0;\n const prev = run.mode === 'resume' ? run.prev?.ta[slot] : undefined;\n if (run.mode === 'resume') {\n if (!prev || prev.kind !== kind) incremental.nonIncremental(`a new ta.${kind}() call`);\n from = run.from;\n // the arrays of the previous run are the run's own: their first values are kept in place\n mem = { kind, machine: prev!.machine, outs: prev!.outs };\n } else {\n mem = { kind, machine: make() as BarStep<unknown[], unknown>, outs: Array.from({ length: outs }, () => []) };\n }\n for (const o of mem.outs) o.length = n;\n for (let i = from; i < n; i++) {\n const r = mem.machine.step(...args(values, i));\n if (outs === 1) mem.outs[0]![i] = typeof r === 'boolean' ? (r ? 1 : 0) : (r as number);\n else for (let k = 0; k < outs; k++) mem.outs[k]![i] = (r as number[])[k]!;\n // the forming bar is not committed: the next update steps it again from the confirmed bars\n if (i < n - 1) mem.machine.commit();\n }\n run.next.ta[slot] = mem;\n const series = mem.outs.map((o) => Series.fromArray(b, o));\n return (outs === 1 ? series[0] : series) as R;\n}\n\nconst at = (v: number[][], k: number, i: number): number => v[k]![i]!;\n\n/** The ta.* calls computed bar by bar in an incremental run (a length given as a Series uses the array function). */\nconst steppedTa = {\n sma: (source: Series, length: number | Series): Series =>\n typeof length === 'number'\n ? stepped('sma', taStep.sma, [source], (v, i) => [at(v, 0, i), length], 1, () => taSeries.sma(source, length))\n : taSeries.sma(source, length),\n ema: (source: Series, length: number): Series =>\n stepped('ema', () => taStep.ema(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.ema(source, length)),\n rma: (source: Series, length: number): Series =>\n stepped('rma', () => taStep.rma(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.rma(source, length)),\n wma: (source: Series, length: number | Series): Series =>\n typeof length === 'number'\n ? stepped('wma', taStep.wma, [source], (v, i) => [at(v, 0, i), length], 1, () => taSeries.wma(source, length))\n : taSeries.wma(source, length),\n rsi: (source: Series, length: number | Series): Series =>\n typeof length === 'number'\n ? stepped('rsi', () => taStep.rsi(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.rsi(source, length))\n : taSeries.rsi(source, length),\n change: (source: Series, length: number = 1): Series =>\n stepped('change', () => taStep.change(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.change(source, length)),\n mom: (source: Series, length: number): Series =>\n stepped('mom', () => taStep.mom(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.mom(source, length)),\n roc: (source: Series, length: number): Series =>\n stepped('roc', () => taStep.roc(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.roc(source, length)),\n cum: (source: Series): Series =>\n stepped('cum', taStep.cum, [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.cum(source)),\n stdev: (source: Series, length: number | Series, biased: boolean = true): Series =>\n typeof length === 'number'\n ? stepped('stdev', taStep.stdev, [source], (v, i) => [at(v, 0, i), length, biased], 1, () => taSeries.stdev(source, length, biased))\n : taSeries.stdev(source, length, biased),\n variance: (source: Series, length: number | Series, biased: boolean = true): Series =>\n typeof length === 'number'\n ? stepped('variance', taStep.variance, [source], (v, i) => [at(v, 0, i), length, biased], 1, () =>\n taSeries.variance(source, length, biased))\n : taSeries.variance(source, length, biased),\n crossover: (a: Series, b: Series | number): Series =>\n stepped('crossover', taStep.crossover, typeof b === 'number' ? [a] : [a, b],\n (v, i) => [at(v, 0, i), typeof b === 'number' ? b : at(v, 1, i)], 1, () => taSeries.crossover(a, b)),\n crossunder: (a: Series, b: Series | number): Series =>\n stepped('crossunder', taStep.crossunder, typeof b === 'number' ? [a] : [a, b],\n (v, i) => [at(v, 0, i), typeof b === 'number' ? b : at(v, 1, i)], 1, () => taSeries.crossunder(a, b)),\n cross: (a: Series, b: Series | number): Series =>\n stepped('cross', taStep.cross, typeof b === 'number' ? [a] : [a, b],\n (v, i) => [at(v, 0, i), typeof b === 'number' ? b : at(v, 1, i)], 1, () => taSeries.cross(a, b)),\n barssince: (condition: Series): Series =>\n stepped('barssince', taStep.barssince, [condition], (v, i) => [at(v, 0, i) === 1], 1, () => taSeries.barssince(condition)),\n valuewhen: (condition: Series, source: Series, occurrence: number): Series =>\n stepped('valuewhen', () => taStep.valuewhen(occurrence), [condition, source], (v, i) => [at(v, 0, i) === 1, at(v, 1, i)], 1,\n () => taSeries.valuewhen(condition, source, occurrence)),\n macd: (source: Series, fastLength: number, slowLength: number, signalLength: number): [Series, Series, Series] =>\n stepped('macd', () => taStep.macd(fastLength, slowLength, signalLength), [source], (v, i) => [at(v, 0, i)], 3, () =>\n taSeries.macd(source, fastLength, slowLength, signalLength)),\n bb: (source: Series, length: number, mult: number): [Series, Series, Series] =>\n stepped('bb', () => taStep.bb(length, mult), [source], (v, i) => [at(v, 0, i)], 3, () => taSeries.bb(source, length, mult)),\n hma: (source: Series, length: number): Series =>\n stepped('hma', () => taStep.hma(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.hma(source, length)),\n dev: (source: Series, length: number): Series =>\n stepped('dev', () => taStep.dev(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.dev(source, length)),\n cci: (source: Series, length: number): Series =>\n stepped('cci', () => taStep.cci(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.cci(source, length)),\n percentrank: (source: Series, length: number): Series =>\n stepped('percentrank', () => taStep.percentrank(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.percentrank(source, length)),\n median: (source: Series, length: number): Series =>\n stepped('median', () => taStep.median(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.median(source, length)),\n linreg: (source: Series, length: number, offset: number = 0): Series =>\n stepped('linreg', () => taStep.linreg(length, offset), [source], (v, i) => [at(v, 0, i)], 1, () =>\n taSeries.linreg(source, length, offset)),\n correlation: (a: Series, b: Series, length: number): Series =>\n stepped('correlation', () => taStep.correlation(length), [a, b], (v, i) => [at(v, 0, i), at(v, 1, i)], 1, () =>\n taSeries.correlation(a, b, length)),\n stoch: (source: Series, highSource: Series, lowSource: Series, length: number): Series =>\n stepped('stoch', () => taStep.stoch(length), [source, highSource, lowSource], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1,\n () => taSeries.stoch(source, highSource, lowSource, length)),\n};\n\n// The library's own `ta` object (bars-first functions) is not a script member.\nconst { ta: _libraryTa, ...taFunctions } = taSeries;\nvoid _libraryTa;\n\n/** ta.* with the chart-implicit (bars-first) functions bound to the context,\n * so scripts call them like `ta.tr(true)`, `ta.atr(14)`. Its members and their documentation: {@link TaNamespace}. */\nconst taMembers = strictNamespace('ta', outsideBarLoops({\n ...taFunctions,\n ...steppedTa,\n tr: (handleNa: boolean = false): Series =>\n stepped('tr', () => taStep.tr(handleNa), [high, low, close], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1, () =>\n taSeries.tr(bars(), handleNa)),\n atr: (length: number): Series =>\n stepped('atr', () => taStep.atr(length), [high, low, close], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1, () =>\n taSeries.atr(bars(), length)),\n sar: (start?: number, inc?: number, max?: number): Series => taSeries.sar(bars(), start, inc, max),\n wpr: (length: number = 14): Series =>\n stepped('wpr', () => taStep.wpr(length), [high, low, close], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1, () =>\n taSeries.wpr(bars(), length)),\n supertrend: (factor: number, atrLength: number): [Series, Series] =>\n stepped('supertrend', () => taStep.supertrend(factor, atrLength), [high, low, close],\n (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 2, () => taSeries.supertrend(bars(), factor, atrLength)),\n dmi: (diLength: number, adxSmoothing: number): [Series, Series, Series] =>\n stepped('dmi', () => taStep.dmi(diLength, adxSmoothing), [high, low, close],\n (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 3, () => taSeries.dmi(bars(), diLength, adxSmoothing)),\n kc: (source: Series, length: number, mult: number, useTrueRange?: boolean): [Series, Series, Series] =>\n taSeries.kc(bars(), source, length, mult, useTrueRange),\n kcw: (source: Series, length?: number, mult?: number, useTrueRange?: boolean): Series =>\n taSeries.kcw(bars(), source, length, mult, useTrueRange),\n ichimoku: (\n conversionPeriods: number,\n basePeriods: number,\n laggingSpan2Periods: number,\n displacement: number\n ): [Series, Series, Series, Series, Series] =>\n taSeries.ichimoku(bars(), conversionPeriods, basePeriods, laggingSpan2Periods, displacement),\n /** `ta.highest(source, length)` or `ta.highest(length)` (source = high). */\n highest: (sourceOrLength: Series | number, length?: number | Series): Series => {\n const source = typeof sourceOrLength === 'number' ? high : sourceOrLength;\n const len = typeof sourceOrLength === 'number' ? sourceOrLength : length!;\n return typeof len === 'number'\n ? stepped('highest', taStep.highest, [source], (v, i) => [at(v, 0, i), len], 1, () => taSeries.highest(source, len))\n : taSeries.highest(source, len);\n },\n /** `ta.lowest(source, length)` or `ta.lowest(length)` (source = low). */\n lowest: (sourceOrLength: Series | number, length?: number | Series): Series => {\n const source = typeof sourceOrLength === 'number' ? low : sourceOrLength;\n const len = typeof sourceOrLength === 'number' ? sourceOrLength : length!;\n return typeof len === 'number'\n ? stepped('lowest', taStep.lowest, [source], (v, i) => [at(v, 0, i), len], 1, () => taSeries.lowest(source, len))\n : taSeries.lowest(source, len);\n },\n /** `ta.highestbars(source, length)` or `ta.highestbars(length)` (source = high); offsets are 0 or negative. */\n highestbars: (sourceOrLength: Series | number, length?: number | Series): Series =>\n typeof sourceOrLength === 'number'\n ? taSeries.highestbars(high, sourceOrLength)\n : taSeries.highestbars(sourceOrLength, length!),\n /** `ta.lowestbars(source, length)` or `ta.lowestbars(length)` (source = low); offsets are 0 or negative. */\n lowestbars: (sourceOrLength: Series | number, length?: number | Series): Series =>\n typeof sourceOrLength === 'number'\n ? taSeries.lowestbars(low, sourceOrLength)\n : taSeries.lowestbars(sourceOrLength, length!),\n /** `ta.vwap(source, anchor?, stdev_mult?)` with the chart volume; the default anchor is a new trading day\n * and the first bar: as in PineScript, the first loaded bars (a day in progress) have a value. On D / W / M\n * charts every bar is a new day (no time zone or session needed); on intraday charts it needs the chart context\n * (timeframe, time zone, session). */\n vwap: ((source: Series, anchor?: Series, stdev_mult?: number): Series | [Series, Series, Series] => {\n const a = anchor ?? vwapAnchor();\n return stdev_mult === undefined ? taSeries.vwap(source, volume, a) : taSeries.vwapBands(source, volume, a, stdev_mult);\n }) as {\n (source: Series, anchor?: Series): Series;\n (source: Series, anchor: Series | undefined, stdev_mult: number): [Series, Series, Series];\n },\n /** `ta.vwma(source, length)` with the chart volume, as PineScript; a third argument gives another volume. */\n vwma: (source: Series, length: number, vol?: Series): Series =>\n stepped('vwma', () => taStep.vwma(length), [source, vol ?? volume], (v, i) => [at(v, 0, i), at(v, 1, i)], 1, () =>\n taSeries.vwma(source, length, vol ?? volume)),\n /** `ta.mfi(source, length)` with the chart volume (PineScript takes 2 arguments). */\n mfi: (source: Series, length: number): Series =>\n stepped('mfi', () => taStep.mfi(length), [source, volume], (v, i) => [at(v, 0, i), at(v, 1, i)], 1, () =>\n taSeries.mfi(source, length, volume)),\n /** `ta.pivothigh(source, leftbars, rightbars)` or `ta.pivothigh(leftbars, rightbars)` (source = high).\n * The value appears `rightbars` bars after the pivot bar, as in PineScript. */\n pivothigh: (sourceOrLeft: Series | number, leftOrRight: number | Series, rightbars?: number | Series): Series =>\n typeof sourceOrLeft === 'number'\n ? taSeries.pivothigh(high, sourceOrLeft, leftOrRight)\n : taSeries.pivothigh(sourceOrLeft, leftOrRight, rightbars!),\n /** `ta.pivotlow(source, leftbars, rightbars)` or `ta.pivotlow(leftbars, rightbars)` (source = low). */\n pivotlow: (sourceOrLeft: Series | number, leftOrRight: number | Series, rightbars?: number | Series): Series =>\n typeof sourceOrLeft === 'number'\n ? taSeries.pivotlow(low, sourceOrLeft, leftOrRight)\n : taSeries.pivotlow(sourceOrLeft, leftOrRight, rightbars!),\n // PineScript variables of the chart bars: `ta.obv`, not `ta.obv()`.\n obv: barsSeries(taSeries.obv),\n pvt: barsSeries(taSeries.pvt),\n accdist: barsSeries(taSeries.accdist),\n nvi: barsSeries(taSeries.nvi),\n pvi: barsSeries(taSeries.pvi),\n iii: barsSeries(taSeries.iii),\n wad: barsSeries(taSeries.wad),\n wvad: barsSeries(taSeries.wvad),\n zigzag: (deviation?: number, depth?: number, backstep?: number): [Series, Series, Series] =>\n taSeries.zigzag(bars(), deviation, depth, backstep),\n}));\n/**\n * Technical analysis: moving averages, oscillators, bands, crosses, pivots and volume indicators. Each function\n * computes a whole Series in one call: call it before any `eachBar()` loop and read a bar's value with `c.get(x)`.\n * @example\n * ```js\n * const fast = ta.ema(close, 12), slow = ta.ema(close, 26);\n * plot(fast, \"Fast\"); plot(slow, \"Slow\");\n * ```\n */\nexport const ta: TaNamespace = taMembers;\nsameKeys<typeof taMembers, TaNamespace>(true);\n\n/**\n * Fills the gaps of a Series: each na value (NaN) becomes the last value that was not na. Values before the first\n * non-na value stay na; +/-Infinity is kept.\n * @param source - The Series to fill.\n * @returns A Series without gaps after its first value.\n * @example\n * ```js\n * const pivot = fixnan(ta.pivothigh(5, 5));\n * plot(pivot, \"Last pivot high\", { style: plot.style_stepline });\n * ```\n */\nexport function fixnan(source: Series): Series;\n/**\n * Fills the gaps of a per-bar colour array: each na entry (`undefined`) becomes the last colour that was not na.\n * @param source - One colour per bar, as made by `color.when()`.\n * @returns A colour array without gaps after its first colour.\n * @example\n * ```js\n * const trendColor = fixnan(color.when(ta.crossover(close, ta.sma(close, 20)), color.green));\n * barcolor(trendColor);\n * ```\n */\nexport function fixnan(source: Array<string | undefined>): Array<string | undefined>;\nexport function fixnan(source: Series | Array<string | undefined>): Series | Array<string | undefined> {\n if (source instanceof Series) return Series.fromArray(ctxBars, fixnanValues(source.toArray()));\n // the colours are the same set: the palette stays\n return withPalette(fixnanValues(source), colorPalettes.get(source));\n}\n\n/**\n * Tells, bar by bar, whether a Series is na (NaN or +/-Infinity): a Series of 1 where it is, 0 elsewhere.\n * @param x - The Series to test.\n * @returns A Series of 1 / 0.\n * @example\n * ```js\n * const ma = ta.sma(close, 50);\n * bgcolor(color.when(na(ma), color.new(color.gray, 90)), { title: \"Warming up\" });\n * ```\n */\nexport function na(x: Series): Series;\n/**\n * Tells whether one value is na: NaN, +/-Infinity, `undefined` or `null` (a colour or a drawing), a deleted drawing,\n * or an empty text. Use it on the numbers of a bar loop.\n * @param x - The value to test.\n * @returns true when the value is na.\n * @example\n * ```js\n * const ma = ta.sma(close, 50);\n * eachBar((c) => { if (!na(c.get(ma)) && c.close > c.get(ma)) label.new(c.i, c.high, \"Above\"); });\n * ```\n */\nexport function na(x: unknown): boolean;\nexport function na(x: unknown): Series | boolean {\n if (x instanceof Series) return Series.fromArray(ctxBars, x.toArray().map((v) => (isNA(v) ? 1 : 0)));\n return x === '' || isNA(x);\n}\n\n/**\n * Replaces the na values of a Series (NaN or +/-Infinity) with a replacement, bar by bar, e.g. to start a sum at 0.\n * @param source - The Series to clean.\n * @param replacement - The value for the na bars: a number, or a Series (its value on the same bar). Default: 0.\n * @returns A Series without na values (unless the replacement is na).\n * @example\n * ```js\n * const change = nz(close.sub(close.offset(1)));\n * plot(change, \"Change\", { style: plot.style_columns });\n * ```\n */\nexport function nz(source: Series, replacement?: number | Series): Series;\n/**\n * Returns a value, or a replacement when it is na (NaN, +/-Infinity, `undefined`, `null`). Use it on the numbers of\n * a bar loop.\n * @param source - The value to check.\n * @param replacement - The value returned when `source` is na. Default: 0.\n * @returns `source`, or `replacement` when `source` is na.\n * @example\n * ```js\n * const total = eachBar((c) => nz(c.prev()) + c.volume);\n * plot(total, \"Cumulative volume\");\n * ```\n */\nexport function nz<T>(source: T, replacement?: T): T;\nexport function nz(source: unknown, replacement: unknown = 0): unknown {\n if (source instanceof Series) {\n const values = source.toArray();\n const rep = replacement instanceof Series ? replacement.toArray() : undefined;\n const r = rep ? 0 : Number(replacement);\n return Series.fromArray(ctxBars, values.map((v, i) => (isNA(v) ? (rep ? rep[i]! : r) : v)));\n }\n return nzValue(source, replacement);\n}\n\n// \u2500\u2500 Color helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * The palette of a per-bar colour array: the constant colours it chooses from (PineScript compiles the colours of a\n * conditional colour expression into a palette, in their order in the expression). An array without one (colours\n * computed per bar) has none: its colours cannot be changed one by one.\n */\nconst colorPalettes = new WeakMap<object, string[]>();\n\nfunction withPalette<T extends object>(colors: T, palette: string[] | undefined): T {\n if (palette?.length) colorPalettes.set(colors, palette);\n return colors;\n}\n\n/** The palette of a colour argument given as a per-bar array, if it has one. */\nfunction paletteOfColors(col: unknown): string[] | undefined {\n return typeof col === 'object' && col !== null ? colorPalettes.get(col) : undefined;\n}\n\n/** Per-bar color selection: truthy \u2192 colorTrue, else colorFalse.\n * colorFalse may be omitted (PineScript `na`): those bars get no color,\n * which bgcolor()/barcolor() skip. */\nfunction colorWhen(cond: Series, colorTrue: string, colorFalse: string): string[];\nfunction colorWhen(cond: Series, colorTrue: string, colorFalse?: string): Array<string | undefined>;\nfunction colorWhen(cond: Series, colorTrue: string, colorFalse?: string): Array<string | undefined> {\n const colors = cond.toArray().map((v) => (!isNA(v) && v !== 0 ? colorTrue : colorFalse));\n const palette = [colorTrue, ...(colorFalse !== undefined && colorFalse !== colorTrue ? [colorFalse] : [])];\n return withPalette(colors, palette);\n}\n\ntype GradientColor = string | null | undefined;\n\n/** PineScript `color.from_gradient(value, bottom_value, top_value, bottom_color, top_color)`. With numbers and\n * colours: one colour. When an argument is a Series (or a colour is a per-bar array, as from `color.when`): the\n * colour of each bar, the rule of the number form applied to the values of that bar (#187), for\n * plot()/fill()/bgcolor()/barcolor(). */\nfunction fromGradient(\n value: number,\n bottom_value: number,\n top_value: number,\n bottom_color: GradientColor,\n top_color: GradientColor\n): string;\nfunction fromGradient(\n value: number | Series,\n bottom_value: number | Series,\n top_value: number | Series,\n bottom_color: GradientColor | readonly GradientColor[],\n top_color: GradientColor | readonly GradientColor[]\n): string | string[];\nfunction fromGradient(\n value: number | Series,\n bottom_value: number | Series,\n top_value: number | Series,\n bottom_color: GradientColor | readonly GradientColor[],\n top_color: GradientColor | readonly GradientColor[]\n): string | string[] {\n const args = [value, bottom_value, top_value];\n if (!args.some((a) => a instanceof Series) && !Array.isArray(bottom_color) && !Array.isArray(top_color)) {\n return colorCore.from_gradient(value as number, bottom_value as number, top_value as number, bottom_color as string, top_color as string);\n }\n const [v, lo, hi] = args.map((a) => (a instanceof Series ? a.toArray() : undefined));\n const at = (arr: number[] | undefined, num: number | Series, i: number) => (arr ? arr[i]! : (num as number));\n const colorAt = (c: GradientColor | readonly GradientColor[], i: number) => (Array.isArray(c) ? c[i] : (c as GradientColor));\n return Array.from({ length: ctxBars.length }, (_, i) =>\n colorCore.from_gradient(at(v, value, i), at(lo, bottom_value, i), at(hi, top_value, i), colorAt(bottom_color, i) as string, colorAt(top_color, i) as string)\n );\n}\n\nconst colorMembers = strictNamespace('color', {\n ...colorCore,\n new: colorCore.new_color,\n from_gradient: fromGradient,\n when: colorWhen,\n /**\n * Not in PineScript: the colour faded by `amount`, from 0 (unchanged) to 1 (invisible): `color.fade(color.red, 0.8)`\n * is `color.new(color.red, 80)`.\n */\n fade: (c: string, amount: number): string => {\n if (typeof amount !== 'number' || !(amount >= 0 && amount <= 1)) {\n throw new ScriptError(`color.fade(): the amount is from 0 (unchanged) to 1 (invisible), got ${shown(amount)}.`);\n }\n return colorCore.new_color(c, amount * 100);\n },\n});\n/**\n * Colours: named colours (`color.red`, `color.teal`...), `color.new` for transparency, `color.rgb`, gradients, and\n * `color.when` to pick a colour per bar for `plot()`, `fill()`, `bgcolor()` and `barcolor()`.\n * @example\n * ```js\n * const up = close.gt(open);\n * plot(close, \"Close\", { color: color.when(up, color.green, color.red) });\n * bgcolor(color.new(color.blue, 90));\n * ```\n */\nexport const color: ColorNamespace = colorMembers;\nsameKeys<typeof colorMembers, ColorNamespace>(true);\n\n// \u2500\u2500 Drawing declarations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Options of {@link plot}. */\nexport interface ScriptPlotOptions {\n /** Shift in bars: the value of bar i is drawn on bar i + offset (negative: to the left). Default: 0. */\n offset?: number;\n /** One colour, or one colour per bar (`color.when()`, `undefined` = not drawn). Default: blue `#2962FF`. */\n color?: string | string[];\n /** Line width in pixels. Default: 1. */\n linewidth?: number;\n /** How the values are drawn: `plot.style_line`, `plot.style_histogram`, `plot.style_columns`... Default: `plot.style_line`. */\n style?: PlotConfig['style'];\n /** Dash pattern of the line: `plot.linestyle_solid`, `plot.linestyle_dashed` or `plot.linestyle_dotted` (one for all bars). Default: solid. */\n linestyle?: PlotConfig['linestyle'];\n /** Where the plot shows: `display.all`, `display.none` (hidden, still listed), `display.pane`, `display.status_line`, `display.data_window`. Default: `display.all`. */\n display?: PlotConfig['display'];\n /** Base level the histogram bars start from (`plot.style_histogram`). Default: 0. */\n histbase?: number;\n /** true: draw on the price pane even when the script has its own pane. Default: false. */\n force_overlay?: boolean;\n /** false: not listed in the style settings of the script. Default: true. */\n editable?: boolean;\n}\n\n/**\n * The titles an output gets when the script gives none (`plot` is \"Plot\", `hline` is \"Level\"...): the style settings\n * and the alert lists show them.\n */\nexport const DEFAULT_OUTPUT_TITLES = {\n /** Title of a `plot()` without one. */\n plot: 'Plot',\n /** Title of an `hline()` without one. */\n hline: 'Level',\n /** Title of a `fill()` between two plots without one. */\n plotFill: 'Plots Background',\n /** Title of a `fill()` between two hlines without one. */\n hlineFill: 'Hlines Background',\n /** Title of a `plotshape()` without one. */\n shape: 'Shapes',\n /** Title of a `plotchar()` without one. */\n char: 'Chars',\n /** Title of a `plotarrow()` without one. */\n arrow: 'Arrows',\n /** Title of a `bgcolor()` without one. */\n bgcolor: 'Background Color',\n /** Title of a `barcolor()` without one. */\n barcolor: 'Bar Color',\n /** Title of a `plotcandle()` without one. */\n candle: 'PlotCandle',\n /** Title of a `plotbar()` without one. */\n bar: 'PlotBar',\n} as const;\n\nconst PLOT_OPTION_KEYS = ['offset', 'color', 'linewidth', 'style', 'linestyle', 'display', 'histbase', 'force_overlay', 'editable'] as const;\n\n/**\n * Draws a Series on the chart (a line by default, or a histogram, columns, area, circles...) and lists it in the\n * legend and the settings. Bars whose value is na (NaN or +/-Infinity) are not drawn.\n * @param source - The values to draw: a Series, or a number for the same value on every bar.\n * @param title - Name of the plot in the legend, the settings and the alerts. Default: \"Plot\".\n * @param options - Colour, width, style, line style, offset, display... Default: `{}` (a blue line).\n * @returns A handle to pass to `fill()`.\n * @example\n * ```js\n * const fast = plot(ta.ema(close, 12), \"Fast\", { color: color.teal, linewidth: 2 });\n * const slow = plot(ta.ema(close, 26), \"Slow\", { color: color.orange });\n * fill(fast, slow, color.new(color.gray, 85));\n * ```\n */\nfunction plotImpl(source: Series | number, title: string = DEFAULT_OUTPUT_TITLES.plot, options: ScriptPlotOptions = {}): PlotHandle {\n if (intrabarRun) return { id: '', kind: 'plot' }; // dropped: an intrabar run's outputs aren't read\n const c = collector();\n if (c.strict && typeof title !== 'string') throw new ScriptError(`plot(): the title is a text, e.g. plot(rsi, \"RSI\"), got ${shown(title)}.`);\n checkOptions('plot', options, PLOT_OPTION_KEYS);\n const series = typeof source === 'number' ? new Series(ctxBars, () => source) : source;\n if (!(series instanceof Series)) {\n throw new TypeError(`plot(): the value to plot is a series (close, ta.sma(close, 14)...) or a number, got ${shown(source)}.`);\n }\n const id = scriptOptions.plotIds === 'title' ? slugId(title, `plot${c.plotConfig.length}`, (c.plotIdsTaken ??= new Set())) : `plot${c.plotConfig.length}`;\n const perBar = Array.isArray(options.color) ? options.color : undefined;\n const palette = scriptOptions.palette === true ? DEFAULT_PALETTE : Array.isArray(scriptOptions.palette) && scriptOptions.palette.length ? scriptOptions.palette : null;\n let fallback = '#2962FF';\n if (palette && options.color === undefined) {\n const k = c.paletteUsed ?? 0;\n c.paletteUsed = k + 1;\n fallback = palette[k % palette.length]!;\n }\n const staticColor = typeof options.color === 'string' ? options.color : (perBar?.[perBar.length - 1] ?? fallback);\n c.plotConfig.push({\n id,\n title,\n color: staticColor,\n lineWidth: options.linewidth,\n style: options.style,\n linestyle: options.linestyle,\n display: options.display,\n histbase: options.histbase,\n forceOverlay: options.force_overlay,\n ...(options.editable === false ? { editable: false } : {}),\n ...(paletteOfColors(perBar) ? { palette: paletteOfColors(perBar) } : {}),\n });\n c.outputs.push({ kind: 'plot', id, title });\n const values = series.toArray();\n const b = bars();\n let data: TimeValue[] = [];\n // offset (PineScript plot(offset = k)): the value and colour of bar i are drawn on bar i + k; bars past the\n // chart's first or last bar are dropped\n const off = Math.trunc(options.offset ?? 0);\n let j0 = Math.max(0, off);\n // An incremental run (#196) keeps the points of the bars whose values did not change; pos[j]: points before bar j\n const run = incremental.active;\n const slot = run ? run.plotSlot++ : -1;\n let pos: number[] = [];\n const prev = run?.mode === 'resume' ? run.prev?.plots[slot] : undefined;\n const sig = `${off}|${perBar ? 'colors' : ''}`;\n if (prev && prev.sig === sig) {\n const from = Math.max(j0, run!.from + Math.min(0, off));\n if (from < prev.pos.length) {\n // the points are given to the host: a copy of the kept ones (the positions are the run's own)\n data = prev.data.slice(0, prev.pos[from]);\n pos = prev.pos;\n pos.length = from;\n j0 = from;\n }\n }\n for (let j = 0; j < j0; j++) pos[j] ??= 0;\n let j = j0;\n for (; j < b.length && j - off < b.length; j++) {\n pos[j] = data.length;\n const i = j - off;\n const value = values[i];\n if (value === undefined || !Number.isFinite(value)) continue; // PineScript plots +/-Infinity as na\n data.push(perBar ? { time: b[j]!.time, value, color: perBar[i] } : { time: b[j]!.time, value });\n }\n for (; j <= b.length; j++) pos[j] = data.length;\n if (run) run.next.plots[slot] = { data, pos, sig };\n c.plots[id] = data;\n return { id, kind: 'plot' };\n}\n\n/** The `plot()` function with its `plot.style_*` and `plot.linestyle_*` constants. */\nexport interface PlotFunction {\n /**\n * Draws a Series on the chart (a line by default, or a histogram, columns, area, circles...) and lists it in the\n * legend and the settings. Bars whose value is na (NaN or +/-Infinity) are not drawn.\n * @param source - The values to draw: a Series, or a number for the same value on every bar.\n * @param title - Name of the plot in the legend, the settings and the alerts. Default: \"Plot\".\n * @param options - Colour, width, style, line style, offset, display... Default: `{}` (a blue line).\n * @returns A handle to pass to `fill()`.\n */\n (source: Series | number, title?: string, options?: ScriptPlotOptions): PlotHandle;\n /** Style: a line through every value; na values are bridged. */\n readonly style_line: 'line';\n /** Style: a line with a gap where the value is na. */\n readonly style_linebr: 'linebr';\n /** Style: steps (horizontal then vertical moves); na values are bridged. */\n readonly style_stepline: 'stepline';\n /** Style: steps with a gap where the value is na. */\n readonly style_steplinebr: 'steplinebr';\n /** Style: steps with a diamond on each change. */\n readonly style_stepline_diamond: 'stepline_diamond';\n /** Style: a thin bar from the base line (`histbase`, default 0) to each value. */\n readonly style_histogram: 'histogram';\n /** Style: a wide column from the base line to each value. */\n readonly style_columns: 'columns';\n /** Style: a line with the area down to the base line filled. */\n readonly style_area: 'area';\n /** Style: a filled area with a gap where the value is na. */\n readonly style_areabr: 'areabr';\n /** Style: a dot on each value. */\n readonly style_circles: 'circles';\n /** Style: a cross on each value. */\n readonly style_cross: 'cross';\n /** Line style: solid. */\n readonly linestyle_solid: 'solid';\n /** Line style: dotted. */\n readonly linestyle_dotted: 'dotted';\n /** Line style: dashed. */\n readonly linestyle_dashed: 'dashed';\n}\n\n/**\n * Draws a Series on the chart and lists it in the legend and the settings; `plot.style_*` and `plot.linestyle_*`\n * pick how it is drawn.\n * @example\n * ```js\n * const fast = plot(ta.ema(close, 12), \"Fast\", { color: color.teal, linewidth: 2 });\n * plot(ta.rsi(close, 14), \"RSI\", { style: plot.style_histogram });\n * ```\n */\nexport const plot: PlotFunction = Object.assign(plotImpl, {\n style_line: 'line',\n style_linebr: 'linebr',\n style_stepline: 'stepline',\n style_steplinebr: 'steplinebr',\n style_stepline_diamond: 'stepline_diamond',\n style_histogram: 'histogram',\n style_columns: 'columns',\n style_area: 'area',\n style_areabr: 'areabr',\n style_circles: 'circles',\n style_cross: 'cross',\n linestyle_solid: 'solid',\n linestyle_dotted: 'dotted',\n linestyle_dashed: 'dashed',\n} as const);\n\nexport interface ScriptHLineOptions {\n /** Colour of the line. Default: the host's (grey). */\n color?: string;\n /** Line style: `hline.style_solid`, `hline.style_dotted` or `hline.style_dashed`. Default: dashed. */\n linestyle?: HLineConfig['linestyle'];\n /** Width of the line in pixels. Default: 1. */\n linewidth?: number;\n /** false: not listed in the style settings of the script. Default: true. */\n editable?: boolean;\n}\n\n/**\n * Draws a horizontal line at a fixed price (a level such as 70 / 30 on an oscillator).\n * @param price - Price of the line.\n * @param title - Name of the line in the settings. Default: \"Level\".\n * @param options - Colour, line style and width. Default: `{}` (a dashed line).\n * @returns A handle to pass to `fill()`.\n */\nfunction hlineImpl(price: number, title: string = DEFAULT_OUTPUT_TITLES.hline, options: ScriptHLineOptions = {}): PlotHandle {\n const c = collector();\n checkOptions('hline', options, ['color', 'linestyle', 'linewidth', 'editable']);\n const id = `hline${c.hlineConfig.length}`;\n c.hlineConfig.push({\n id,\n price,\n title,\n color: options.color,\n linestyle: options.linestyle ?? 'dashed',\n linewidth: options.linewidth,\n ...(options.editable === false ? { editable: false } : {}),\n });\n return { id, kind: 'hline' };\n}\n\n/** The `hline()` function with its `hline.style_*` constants. */\nexport interface HlineFunction {\n /**\n * Draws a horizontal line at a fixed price (a level such as 70 / 30 on an oscillator).\n * @param price - Price of the line.\n * @param title - Name of the line in the settings. Default: \"Level\".\n * @param options - Colour, line style and width. Default: `{}` (a dashed line).\n * @returns A handle to pass to `fill()`.\n */\n (price: number, title?: string, options?: ScriptHLineOptions): PlotHandle;\n /** Line style: solid. */\n readonly style_solid: 'solid';\n /** Line style: dotted. */\n readonly style_dotted: 'dotted';\n /** Line style: dashed (the default). */\n readonly style_dashed: 'dashed';\n}\n\n/**\n * Draws a horizontal line at a fixed price; `hline.style_*` picks its line style.\n * @example\n * ```js\n * const top = hline(70, \"Overbought\", { color: color.red });\n * const bottom = hline(30, \"Oversold\", { linestyle: hline.style_dotted });\n * fill(top, bottom, color.new(color.purple, 90));\n * ```\n */\nexport const hline: HlineFunction = Object.assign(hlineImpl, {\n style_solid: 'solid',\n style_dotted: 'dotted',\n style_dashed: 'dashed',\n} as const);\n\nexport interface ScriptFillOptions {\n /** Fill colour: one colour, or one per bar from `color.when()`. */\n color?: string | string[];\n /** Name of the fill in the settings. Default: \"Plots Background\" / \"Hlines Background\". */\n title?: string;\n /** false: not listed in the style settings of the script. Default: true. */\n editable?: boolean;\n}\n\n/** A fill colour argument: a colour, na (null / undefined), or a per-bar array from color.when(). */\nexport type ScriptFillColor = string | null | undefined | Array<string | null | undefined>;\n\n/** A gradient value argument: a number or a Series. */\nexport type ScriptFillValue = number | Series;\n\nfunction perBarValues(v: ScriptFillValue, n: number): number[] {\n return v instanceof Series ? v.toArray().slice(0, n) : new Array<number>(n).fill(v);\n}\n\nfunction perBarColors(c: ScriptFillColor, n: number): Array<string | null> {\n if (Array.isArray(c)) return Array.from({ length: n }, (_, i) => c[i] ?? null);\n return new Array<string | null>(n).fill(c ?? null);\n}\n\n/** The colour of every bar when it is the same on all of them (and not na). */\nfunction sameColor(colors: Array<string | null>): string | undefined {\n const first = colors[0];\n return first && colors.every((x) => x === first) ? first : undefined;\n}\n\n/**\n * Colours the space between two plots or two hlines, with an options object.\n * @param a - First plot or hline (the handle `plot()` / `hline()` returned).\n * @param b - Second plot or hline, of the same kind as `a`.\n * @param options - Colour (one, or one per bar from `color.when()`), title, editable. Default: `{}`.\n * @example\n * ```js\n * const upper = plot(ta.sma(high, 20), \"Upper\");\n * const lower = plot(ta.sma(low, 20), \"Lower\");\n * fill(upper, lower, { color: color.new(color.blue, 85), title: \"Channel\" });\n * ```\n */\nexport function fill(a: PlotHandle, b: PlotHandle, options?: ScriptFillOptions): void;\n/**\n * Colours the space between two plots or two hlines with one colour (or one per bar).\n * @param a - First plot or hline (the handle `plot()` / `hline()` returned).\n * @param b - Second plot or hline, of the same kind as `a`.\n * @param color - Fill colour, or one per bar from `color.when()`; na (null) leaves a bar unfilled.\n * @param title - Name of the fill in the settings. Default: \"Plots Background\" / \"Hlines Background\".\n * @param rest - `editable` (false keeps it out of the settings); `show_last`, `fillgaps` and `display` are accepted\n * and not used.\n * @example\n * ```js\n * const top = hline(70), bottom = hline(30);\n * fill(top, bottom, color.new(color.purple, 90), \"Zone\");\n * ```\n */\nexport function fill(a: PlotHandle, b: PlotHandle, color: ScriptFillColor, title?: string, ...rest: unknown[]): void;\n/**\n * Colours the space between two plots with a gradient: `top_color` at `top_value`, `bottom_color` at\n * `bottom_value`; the values and colours may change from bar to bar.\n * @param a - First plot (the handle `plot()` returned).\n * @param b - Second plot.\n * @param top_value - Price of the top colour: a number or a Series.\n * @param bottom_value - Price of the bottom colour: a number or a Series.\n * @param top_color - Colour at the top, or one per bar.\n * @param bottom_color - Colour at the bottom, or one per bar.\n * @param title - Name of the fill in the settings. Default: \"Plots Background\".\n * @param rest - `editable` (false keeps it out of the settings); other arguments are accepted and not used.\n * @example\n * ```js\n * const basis = ta.sma(close, 20);\n * const p = plot(close), q = plot(basis);\n * fill(p, q, high, basis, color.green, color.new(color.green, 100));\n * ```\n */\nexport function fill(\n a: PlotHandle,\n b: PlotHandle,\n top_value: ScriptFillValue,\n bottom_value: ScriptFillValue,\n top_color: ScriptFillColor,\n bottom_color: ScriptFillColor,\n title?: string,\n ...rest: unknown[]\n): void;\nexport function fill(a: PlotHandle, b: PlotHandle, ...args: unknown[]): void {\n if (intrabarRun) return; // dropped: an intrabar run's outputs aren't read\n const c = collector();\n const third = args[0];\n let perBar: string[] | undefined;\n let staticColor: string | undefined;\n let title: string | undefined;\n let gradient: FillGradient | undefined;\n let editable: unknown;\n /** The per-bar colour argument as given (its palette) */\n let perBarArg: unknown;\n if (typeof third === 'number' || third instanceof Series) {\n const n = ctxBars.bars.length;\n gradient = {\n topValue: perBarValues(third, n),\n bottomValue: perBarValues(args[1] as ScriptFillValue, n),\n topColor: perBarColors(args[2] as ScriptFillColor, n),\n bottomColor: perBarColors(args[3] as ScriptFillColor, n),\n };\n title = args[4] as string | undefined;\n editable = args[5];\n } else if (third !== null && typeof third === 'object' && !Array.isArray(third)) {\n const options = third as ScriptFillOptions;\n perBar = Array.isArray(options.color) ? options.color : undefined;\n perBarArg = perBar;\n staticColor = typeof options.color === 'string' ? options.color : undefined;\n title = options.title;\n editable = options.editable;\n } else {\n const color = third as ScriptFillColor;\n perBar = Array.isArray(color) ? color.map((x) => x ?? '') : undefined;\n perBarArg = Array.isArray(color) ? color : undefined;\n staticColor = typeof color === 'string' ? color : undefined;\n title = args[1] as string | undefined;\n editable = args[2];\n }\n const id = `fill${c.fillConfig.length}`;\n title ??= a.kind === 'hline' && b.kind === 'hline' ? DEFAULT_OUTPUT_TITLES.hlineFill : DEFAULT_OUTPUT_TITLES.plotFill;\n const topColor = gradient && sameColor(gradient.topColor);\n const bottomColor = gradient && sameColor(gradient.bottomColor);\n const hlines = a.kind === 'hline' && b.kind === 'hline';\n c.fillConfig.push({\n id,\n plot1: a.id,\n plot2: b.id,\n color: staticColor,\n // the per-bar data of a fill between plots is in the result\n ...(hlines ? { colors: perBar, gradient } : {}),\n title,\n ...(topColor ? { topColor } : {}),\n ...(bottomColor ? { bottomColor } : {}),\n ...(editable === false ? { editable: false } : {}),\n ...(paletteOfColors(perBarArg) ? { palette: paletteOfColors(perBarArg) } : {}),\n });\n if (hlines) return;\n c.fills.push({\n id,\n plot1: a.id,\n plot2: b.id,\n options: { color: staticColor, title },\n colors: perBar,\n gradient,\n });\n}\n\nexport interface PlotShapeOptions {\n style?: ShapeStyle;\n location?: MarkerLocation;\n color?: string;\n text?: string;\n textcolor?: string;\n size?: MarkerSize;\n /** Display offset in bars (marker shown at bar i + offset). */\n offset?: number;\n /** Hover tooltip (extension over PineScript, for label.new-style ports). */\n tooltip?: string;\n /** Draw on the main chart pane even when the script is not an overlay (PineScript `force_overlay`); default false. */\n force_overlay?: boolean;\n /** False: not listed in the Style settings of the study (PineScript `editable`); default true. */\n editable?: boolean;\n}\n\nexport interface PlotCharOptions extends Omit<PlotShapeOptions, 'style'> {\n char?: string;\n}\n\n/** PineScript shape.* style -> marker shape. */\nconst MARKER_SHAPES: Record<ShapeStyle, MarkerShape> = {\n xcross: 'xcross',\n cross: 'cross',\n triangleup: 'triangleUp',\n triangledown: 'triangleDown',\n flag: 'flag',\n circle: 'circle',\n arrowup: 'arrowUp',\n arrowdown: 'arrowDown',\n labelup: 'labelUp',\n labeldown: 'labelDown',\n square: 'square',\n diamond: 'diamond',\n};\n\n/**\n * Marker position of a PineScript location. With location.absolute the shape sits on the price: a label pointing\n * down above it, a label pointing up below it, the other shapes (and the characters) centred on it.\n */\nfunction markerPosition(location: MarkerLocation, shape: ShapeStyle | undefined): MarkerPosition {\n switch (location) {\n case 'abovebar':\n return 'aboveBar';\n case 'belowbar':\n return 'belowBar';\n case 'top':\n return 'top';\n case 'bottom':\n return 'bottom';\n case 'absolute':\n return shape === 'labeldown' ? 'atPriceTop' : shape === 'labelup' ? 'atPriceBottom' : 'atPriceMiddle';\n }\n}\n\n/** Default colour of plotshape / plotchar markers. */\nconst MARKER_COLOR = '#2962FF';\n\n/** The value of an output's series on each bar where it is not na (a condition: 1 or 0), at the bar it was computed\n * on: what PineScript gives for the output in an alert message. */\nfunction outputSeries(values: ArrayLike<unknown>, b: readonly Bar[]): TimeValue[] {\n const series: TimeValue[] = [];\n for (let i = 0; i < b.length; i++) {\n const v = values[i];\n if (typeof v === 'number' && Number.isFinite(v)) series.push({ time: b[i]!.time, value: v });\n else if (typeof v === 'boolean') series.push({ time: b[i]!.time, value: v ? 1 : 0 });\n }\n return series;\n}\n\n/** Shared emitter for plotshape()/plotchar(). Emits one marker per bar where\n * the condition is truthy (not na, not 0). A plotchar marker has the shape 'circle' and its character in `char`. */\nfunction emitMarkers(\n kind: 'shape' | 'char',\n condition: Series,\n title: string | undefined,\n options: PlotShapeOptions & PlotCharOptions\n): void {\n if (intrabarRun) return; // dropped: an intrabar run's outputs aren't read\n const c = collector();\n const id = `${kind}${c.shapeConfig.filter((s) => s.kind === kind).length}`;\n title ??= DEFAULT_OUTPUT_TITLES[kind];\n const style: ShapeStyle | 'char' = kind === 'shape' ? (options.style ?? 'xcross') : 'char';\n const char = kind === 'char' ? (options.char ?? '*') : undefined;\n const location = options.location ?? 'abovebar';\n c.shapeConfig.push({\n id,\n kind,\n title,\n style: kind === 'shape' ? (style as ShapeStyle) : undefined,\n char,\n location,\n color: options.color,\n text: options.text,\n textcolor: options.textcolor,\n size: options.size,\n offset: options.offset,\n forceOverlay: options.force_overlay,\n ...(options.editable === false ? { editable: false } : {}),\n });\n c.outputs.push({ kind, id, title });\n const shapeStyle = kind === 'shape' ? (style as ShapeStyle) : undefined;\n const template: Omit<MarkerData, 'time'> = {\n position: markerPosition(location, shapeStyle),\n shape: shapeStyle ? MARKER_SHAPES[shapeStyle] : 'circle',\n color: options.color ?? MARKER_COLOR,\n id,\n };\n if (char !== undefined) template.char = char;\n if (options.text !== undefined) template.text = options.text;\n if (options.textcolor !== undefined) template.textColor = options.textcolor;\n if (options.size !== undefined) template.size = options.size;\n if (options.tooltip !== undefined) template.tooltip = options.tooltip;\n if (options.force_overlay) template.forceOverlay = true;\n const values = condition.toArray();\n const b = bars();\n const off = options.offset ?? 0;\n c.outputValues[id] = outputSeries(values, b);\n for (let i = 0; i < b.length; i++) {\n const v = values[i];\n if (v === undefined || Number.isNaN(v) || v === 0) continue;\n const j = i + off;\n if (j < 0 || j >= b.length) continue;\n const time = b[j]!.time;\n c.markers.push(location === 'absolute' ? { time, ...template, price: v } : { time, ...template });\n }\n}\n\nconst SHAPE_OPTION_KEYS = ['style', 'location', 'color', 'text', 'textcolor', 'size', 'offset', 'tooltip', 'force_overlay', 'editable'] as const;\n\n/**\n * Draws a shape (triangle, arrow, circle, label...) on each bar where the condition is true: buy and sell signals.\n * @param condition - Series that is true (non-zero) on the bars that get a shape. With `location.absolute`, its\n * value is the price of the shape.\n * @param title - Name of the shapes in the settings and the alerts. Default: \"Shapes\".\n * @param options - Shape (`shape.*`), place (`location.*`), colour, text, size (`size.*`), offset... Default: `{}`\n * (a cross above the bar).\n * @example\n * ```js\n * const up = ta.crossover(ta.ema(close, 9), ta.ema(close, 21));\n * plotshape(up, \"Buy\", { style: shape.triangleup, location: location.belowbar, color: color.green });\n * ```\n */\nexport function plotshape(condition: Series, title?: string, options: PlotShapeOptions = {}): void {\n checkOptions('plotshape', options, SHAPE_OPTION_KEYS, ['color', 'textcolor']);\n emitMarkers('shape', condition, title, options);\n}\n\n/**\n * Draws a character (a letter, an emoji...) on each bar where the condition is true.\n * @param condition - Series that is true (non-zero) on the bars that get the character. With `location.absolute`,\n * its value is the price of the character.\n * @param title - Name of the characters in the settings and the alerts. Default: \"Chars\".\n * @param options - Character (`char`), place (`location.*`), colour, text, size (`size.*`), offset... Default: `{}`\n * (a star above the bar).\n * @example\n * ```js\n * const gapUp = open.gt(high.offset(1));\n * plotchar(gapUp, \"Gap up\", { char: \"\u25B2\", location: location.abovebar, color: color.teal });\n * ```\n */\nexport function plotchar(condition: Series, title?: string, options: PlotCharOptions = {}): void {\n checkOptions('plotchar', options, [...SHAPE_OPTION_KEYS.filter((k) => k !== 'style'), 'char'], ['color', 'textcolor']);\n emitMarkers('char', condition, title, options);\n}\n\nexport interface PlotArrowOptions {\n /** Colour of the up arrows: one colour or one per bar. Default: #00FF00. */\n colorup?: string | Array<string | undefined>;\n /** Colour of the down arrows: one colour or one per bar. Default: #FF0000. */\n colordown?: string | Array<string | undefined>;\n /** Moves the arrows by this many bars (the arrow of bar i is drawn on bar i + offset). Default: 0. */\n offset?: number;\n /** Height of the smallest arrow, in pixels. Default: 5. */\n minheight?: number;\n /** Height of the largest arrow, in pixels. Default: 100. */\n maxheight?: number;\n /** Where the arrows are shown: `display.all`, `display.none`... Default: everywhere. */\n display?: ArrowConfig['display'];\n /** Draw on the main chart pane even when the script is not an overlay (PineScript `force_overlay`); default false. */\n force_overlay?: boolean;\n /** False: not listed in the Style settings of the study (PineScript `editable`); default true. */\n editable?: boolean;\n}\n\n/**\n * Draws an up arrow below the bar where the value is positive and a down arrow above it where it is negative;\n * nothing for 0 or na. The larger the value, the longer the arrow (between `minheight` and `maxheight`).\n * @param series - Series whose sign gives the arrow's direction and whose size gives its length.\n * @param title - Name of the arrows in the settings and the alerts. Default: \"Arrows\".\n * @param options - Colours, heights, offset, display. Default: `{}` (green up, red down).\n * @example\n * ```js\n * const change = close.sub(close.offset(1));\n * plotarrow(change, \"Change\", { colorup: color.teal, colordown: color.orange });\n * ```\n */\nexport function plotarrow(series: Series, title?: string, options: PlotArrowOptions = {}): void {\n if (intrabarRun) return; // dropped: an intrabar run's outputs aren't read\n const c = collector();\n const id = `arrow${c.arrowConfig.length}`;\n title ??= DEFAULT_OUTPUT_TITLES.arrow;\n const pick = (col: string | Array<string | undefined> | undefined, fallback: string, i: number): string | undefined =>\n col === undefined ? fallback : typeof col === 'string' ? col : col[i];\n const colorup = typeof options.colorup === 'string' ? options.colorup : '#00FF00';\n const colordown = typeof options.colordown === 'string' ? options.colordown : '#FF0000';\n c.arrowConfig.push({\n id,\n title,\n colorup,\n colordown,\n minheight: options.minheight ?? 5,\n maxheight: options.maxheight ?? 100,\n offset: options.offset,\n display: options.display,\n forceOverlay: options.force_overlay,\n ...(options.editable === false ? { editable: false } : {}),\n });\n c.outputs.push({ kind: 'arrow', id, title });\n const values = series.toArray();\n const b = bars();\n const off = options.offset ?? 0;\n c.outputValues[id] = outputSeries(values, b);\n for (let i = 0; i < b.length; i++) {\n const v = values[i];\n if (v === undefined || Number.isNaN(v) || v === 0) continue;\n const j = i + off;\n if (j < 0 || j >= b.length) continue;\n const color = v > 0 ? pick(options.colorup, '#00FF00', i) : pick(options.colordown, '#FF0000', i);\n if (color === undefined) continue; // na color: no arrow\n c.arrows.push({ time: b[j]!.time, id, value: v, color });\n }\n}\n\n/** Shared emitter for bgcolor()/barcolor(). A static color applies to every\n * bar; a per-bar array (from color.when) skips undefined entries. The offset\n * is baked in: the color computed at bar i lands on bar i + offset. */\nfunction emitBarColors(\n kind: 'bgcolor' | 'barcolor',\n colors: string | Array<string | undefined>,\n options: { offset?: number; title?: string; force_overlay?: boolean; editable?: boolean }\n): void {\n if (intrabarRun) return; // dropped: an intrabar run's outputs aren't read\n const c = collector();\n const id = `${kind}${c.barColorConfig.filter((x) => x.kind === kind).length}`;\n c.barColorConfig.push({\n id,\n kind,\n title: options.title ?? DEFAULT_OUTPUT_TITLES[kind],\n offset: options.offset,\n forceOverlay: options.force_overlay,\n // a constant colour is a palette of one colour (PineScript); per-bar colours from constants keep theirs\n ...(typeof colors === 'string' ? { palette: [colors] } : paletteOfColors(colors) ? { palette: paletteOfColors(colors) } : {}),\n ...(options.editable === false ? { editable: false } : {}),\n outputIndex: c.outputs.length,\n });\n const b = bars();\n const off = options.offset ?? 0;\n const target: BgColorData[] = kind === 'bgcolor' ? c.bgColors : c.barColors;\n const forceOverlay = kind === 'bgcolor' && options.force_overlay === true;\n for (let i = 0; i < b.length; i++) {\n const col = typeof colors === 'string' ? colors : colors[i];\n if (!col) continue;\n const j = i + off;\n if (j < 0 || j >= b.length) continue;\n target.push(forceOverlay ? { time: b[j]!.time, color: col, id, forceOverlay } : { time: b[j]!.time, color: col, id });\n }\n}\n\n/**\n * Colours the background of the script's pane behind each bar.\n * @param colors - One colour for every bar, or one per bar from `color.when()` (no colour on an na entry).\n * @param options - `offset` (bars to move the colours by), `title` (default \"Background Color\"), `force_overlay`\n * (true: colour the price chart's pane), `editable`. Default: `{}`.\n * @example\n * ```js\n * const rsi = ta.rsi(close, 14);\n * bgcolor(color.when(rsi.gt(70), color.new(color.red, 85)));\n * ```\n */\nexport function bgcolor(\n colors: string | Array<string | undefined>,\n options: { offset?: number; title?: string; force_overlay?: boolean; editable?: boolean } = {}\n): void {\n if (ctx?.strict) checkColor('bgcolor(): the colour', colors);\n checkOptions('bgcolor', options, ['offset', 'title', 'force_overlay', 'editable']);\n emitBarColors('bgcolor', colors, options);\n}\n\n/**\n * Colours the chart's candles or bars, replacing their usual colours.\n * @param colors - One colour for every bar, or one per bar from `color.when()` (usual colour on an na entry).\n * @param options - `title` (default \"Bar Color\") and `editable`. Default: `{}`.\n * @example\n * ```js\n * const trendUp = close.gt(ta.sma(close, 50));\n * barcolor(color.when(trendUp, color.green, color.red));\n * ```\n */\nexport function barcolor(\n colors: string | Array<string | undefined>,\n options: { title?: string; editable?: boolean } = {}\n): void {\n if (ctx?.strict) checkColor('barcolor(): the colour', colors);\n checkOptions('barcolor', options, ['title', 'editable']);\n emitBarColors('barcolor', colors, options);\n}\n\n/** A colour argument of plotcandle() / plotbar(): a colour, or per-bar colours (null / undefined entries are na). */\nexport type ScriptCandleColor = string | Array<string | null | undefined>;\n\nexport interface PlotCandleOptions {\n /** Body colour: one colour or one per bar (`color.when()`); an na entry gives a see-through body. Default: #2962FF. */\n color?: ScriptCandleColor;\n /** Wick colour: one colour or one per bar. Default: #737375. */\n wickcolor?: ScriptCandleColor;\n /** Border colour: one colour or one per bar. Default: #000000. */\n bordercolor?: ScriptCandleColor;\n /** Where the candles are shown: `display.all`, `display.none`... Default: everywhere. */\n display?: CandleConfig['display'];\n /** Draw on the main chart pane even when the script is not an overlay (PineScript `force_overlay`); default false. */\n force_overlay?: boolean;\n /** False: not listed in the Style settings of the study (PineScript `editable`); default true. */\n editable?: boolean;\n}\n\nexport interface PlotBarOptions {\n /** Bar colour: one colour or one per bar (`color.when()`); an na entry gives a see-through bar. Default: #2962FF. */\n color?: ScriptCandleColor;\n /** Where the bars are shown: `display.all`, `display.none`... Default: everywhere. */\n display?: CandleConfig['display'];\n /** Draw on the main chart pane even when the script is not an overlay (PineScript `force_overlay`); default false. */\n force_overlay?: boolean;\n /** False: not listed in the Style settings of the study (PineScript `editable`); default true. */\n editable?: boolean;\n}\n\n/** Colour of bar i: undefined when the argument is not given, 'transparent' for an na entry. */\nfunction candleColor(col: ScriptCandleColor | undefined, i: number): string | undefined {\n if (col === undefined) return undefined;\n if (typeof col === 'string') return col;\n return col[i] ?? 'transparent';\n}\n\ninterface OhlcRow {\n i: number;\n open: number;\n high: number;\n low: number;\n close: number;\n}\n\n/** The bars where open, high, low and close are all not na (PineScript draws no candle / bar otherwise). */\nfunction ohlcRows(o: Series, h: Series, l: Series, cl: Series): OhlcRow[] {\n const [ov, hv, lv, cv] = [o.toArray(), h.toArray(), l.toArray(), cl.toArray()];\n const rows: OhlcRow[] = [];\n for (let i = 0; i < bars().length; i++) {\n const [open, high, low, close] = [ov[i]!, hv[i]!, lv[i]!, cv[i]!];\n if (Number.isFinite(open) && Number.isFinite(high) && Number.isFinite(low) && Number.isFinite(close)) {\n rows.push({ i, open, high, low, close });\n }\n }\n return rows;\n}\n\nconst staticColor = (col: ScriptCandleColor | undefined): string | undefined => (typeof col === 'string' ? col : undefined);\n\n/**\n * Colours of a plotcandle / plotbar argument left out, as the PineScript compiler declares them and the chart draws\n * them (reference: body / bar #2962FF, wick #737375, border #000000; the wick and border do not follow the body).\n */\nexport const DEFAULT_CANDLE_COLORS = {\n /** Body colour (and the colour of `plotbar()` bars). */\n color: '#2962FF',\n /** Wick colour. */\n wickColor: '#737375',\n /** Border colour. */\n borderColor: '#000000',\n} as const;\n\n/** The palettes of the per-bar colour arguments of a plotcandle / plotbar that have one. */\nfunction candlePalettes(cols: { color?: ScriptCandleColor; wickColor?: ScriptCandleColor; borderColor?: ScriptCandleColor }): { palettes?: CandleConfig['palettes'] } {\n const palettes: NonNullable<CandleConfig['palettes']> = {};\n for (const k of ['color', 'wickColor', 'borderColor'] as const) {\n const pal = paletteOfColors(cols[k]);\n if (pal) palettes[k] = pal;\n }\n return Object.keys(palettes).length ? { palettes } : {};\n}\n\n/** A colour argument, or the default when it is left out. */\nconst orDefault = (col: ScriptCandleColor | undefined, fallback: string): ScriptCandleColor => (col === undefined ? fallback : col);\n\n/**\n * Draws candles from four Series (for example the candles of another symbol, or smoothed prices). A bar where one of\n * the four values is na has no candle.\n * @param open - Open of each candle.\n * @param high - High of each candle.\n * @param low - Low of each candle.\n * @param close - Close of each candle.\n * @param title - Name of the candles in the settings. Default: \"PlotCandle\".\n * @param options - Body, wick and border colours, display, force_overlay, editable. Default: `{}`.\n * @example\n * ```js\n * const o = ta.ema(open, 5), h = ta.ema(high, 5), l = ta.ema(low, 5), c = ta.ema(close, 5);\n * plotcandle(o, h, l, c, \"Smoothed\", { color: color.when(c.gt(o), color.teal, color.red) });\n * ```\n */\nexport function plotcandle(\n open: Series,\n high: Series,\n low: Series,\n close: Series,\n title?: string,\n options: PlotCandleOptions = {}\n): void {\n if (intrabarRun) return; // dropped: an intrabar run's outputs aren't read\n const c = collector();\n const color = orDefault(options.color, DEFAULT_CANDLE_COLORS.color);\n const wickcolor = orDefault(options.wickcolor, DEFAULT_CANDLE_COLORS.wickColor);\n const bordercolor = orDefault(options.bordercolor, DEFAULT_CANDLE_COLORS.borderColor);\n const id = `plotcandle${c.candleConfig.filter((x) => x.kind === 'candle').length}`;\n title ??= DEFAULT_OUTPUT_TITLES.candle;\n c.candleConfig.push({\n id,\n kind: 'candle',\n title,\n color: staticColor(color),\n wickColor: staticColor(wickcolor),\n borderColor: staticColor(bordercolor),\n ...candlePalettes({ color, wickColor: wickcolor, borderColor: bordercolor }),\n display: options.display,\n forceOverlay: options.force_overlay,\n ...(options.editable === false ? { editable: false } : {}),\n });\n c.outputs.push({ kind: 'candle', id, title });\n const b = bars();\n c.plotCandles[id] = ohlcRows(open, high, low, close).map(({ i, ...ohlc }) => {\n const candle: PlotCandleData = { time: b[i]!.time, ...ohlc };\n const body = candleColor(color, i);\n const wickColor = candleColor(wickcolor, i);\n const borderColor = candleColor(bordercolor, i);\n if (body !== undefined) candle.color = body;\n if (wickColor !== undefined) candle.wickColor = wickColor;\n if (borderColor !== undefined) candle.borderColor = borderColor;\n if (options.force_overlay) candle.forceOverlay = true;\n return candle;\n });\n}\n\n/**\n * Draws open-high-low-close bars from four Series. A bar where one of the four values is na is not drawn.\n * @param open - Open of each bar.\n * @param high - High of each bar.\n * @param low - Low of each bar.\n * @param close - Close of each bar.\n * @param title - Name of the bars in the settings. Default: \"PlotBar\".\n * @param options - Colour, display, force_overlay, editable. Default: `{}`.\n * @example\n * ```js\n * plotbar(open, high, low, close, \"Bars\", { color: color.when(close.gt(open), color.green, color.red) });\n * ```\n */\nexport function plotbar(\n open: Series,\n high: Series,\n low: Series,\n close: Series,\n title?: string,\n options: PlotBarOptions = {}\n): void {\n if (intrabarRun) return; // dropped: an intrabar run's outputs aren't read\n const c = collector();\n const barColor = orDefault(options.color, DEFAULT_CANDLE_COLORS.color);\n const id = `plotbar${c.candleConfig.filter((x) => x.kind === 'bar').length}`;\n title ??= DEFAULT_OUTPUT_TITLES.bar;\n c.candleConfig.push({\n id,\n kind: 'bar',\n title,\n color: staticColor(barColor),\n ...candlePalettes({ color: barColor }),\n display: options.display,\n forceOverlay: options.force_overlay,\n ...(options.editable === false ? { editable: false } : {}),\n });\n c.outputs.push({ kind: 'bar', id, title });\n const b = bars();\n c.plotBars[id] = ohlcRows(open, high, low, close).map(({ i, ...ohlc }) => {\n const bar: PlotBarData = { time: b[i]!.time, ...ohlc };\n const color = candleColor(barColor, i);\n if (color !== undefined) bar.color = color;\n if (options.force_overlay) bar.forceOverlay = true;\n return bar;\n });\n}\n\n// \u2500\u2500 Per-bar execution (eachBar) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * The scalar view of one bar handed to an {@link eachBar} callback.\n * All fields are plain numbers, so native JS operators work.\n */\nexport interface BarContext {\n /** Bar index (PineScript bar_index). */\n readonly i: number;\n /** Total number of bars. */\n readonly n: number;\n /** Time of the current bar. */\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 /** Value of any Series at the current bar minus `offset` (PineScript src[offset]). */\n get(src: Series, offset?: number): number;\n /** This block's own previous output (PineScript self-reference, offset >= 1). */\n prev(offset?: number): number;\n}\n\n/**\n * Runs the callback once per bar, in order, and collects the returned values\n * into a Series. This is the escape hatch for PineScript logic the vectorized\n * model cannot express:\n *\n * - `var x = 0` / `x := ...` \u2192 a plain `let` variable captured by the closure\n * - per-bar `if` / `for` / `while` \u2192 native JS statements\n * - `src[k]` \u2192 `c.get(src, k)`; self-reference \u2192 `c.prev()`\n *\n * Returning a boolean collects 1/0; returning nothing collects na (NaN).\n *\n * ```typescript\n * let dir = 0; // var dir = 0\n * const trend = eachBar((c) => {\n * if (c.close > c.get(close, 1)) dir = 1; // dir := 1\n * else if (c.close < c.get(close, 1)) dir = -1;\n * return dir;\n * });\n * ```\n */\n/** Initial history buffer of a script series and its growth factor (measured, issue #149). */\nconst HISTORY_START = 242;\nconst HISTORY_GROWTH = 1.618034;\n\n/**\n * History buffer of one script series in eachBar(), as PineScript grows it (measured on PineScript, issue #149):\n * the buffer starts with 242 bars; when the largest reference of a bar goes past it, a jump (the reference grew by\n * more than 1 since the previous bar) sets the buffer to the reference, and a step of 1 grows it to\n * round(size * 1.618034); a buffer above 5000 stops the script on the next bar (RE10008), with that size as\n * \"bars back\". A reference above 5000 stops it at once.\n */\ninterface HistoryBuffer {\n size: number;\n previous: number;\n barMax: number;\n}\n\n/** The outer variables an eachBar() callback changes, by callback source (the same callback on every run). */\nconst outerWritesCache = new Map<string, string[]>();\nfunction outerWritesOf(fn: (...args: never[]) => unknown): string[] {\n const src = fn.toString();\n let found = outerWritesCache.get(src);\n if (!found) {\n found = outerWrites(src);\n if (outerWritesCache.size > 500) outerWritesCache.clear();\n outerWritesCache.set(src, found);\n }\n return found;\n}\n\n/**\n * Runs a function on every bar, oldest first, for logic that needs the bar's values one at a time (state, ifs,\n * loops). The function reads the bar through `c` (`c.close`, `c.get(series)`, `c.get(series, 1)` for one bar back)\n * and returns the bar's value of the Series that `eachBar` gives back (na when it returns nothing).\n * @param fn - Called once per bar with the bar's context; returns a number (or true / false) for that bar.\n * @returns Series of the values the function returned.\n * @example\n * ```js\n * const fast = ta.sma(close, 10);\n * let count = 0;\n * const streak = eachBar((c) => (count = c.get(close) > c.get(fast) ? count + 1 : 0));\n * plot(streak, \"Bars above\");\n * ```\n */\nexport function eachBar(fn: (c: BarContext) => number | boolean | void): Series {\n return runBlock(fn);\n}\n\n/** State an eachBar() block keeps in its incremental checkpoint besides the script's (the strategy engine). */\ninterface BlockExtra {\n save(): unknown;\n restore(state: unknown): void;\n}\n\nfunction runBlock(\n fn: (c: BarContext) => number | boolean | void,\n extra?: BlockExtra,\n /** The script's own callback, when fn wraps it (strategy.eachBar) */\n own: (c: BarContext) => number | boolean | void = fn\n): Series {\n collector(); // same lifecycle guard (and error message) as the declaration calls\n const b = bars();\n // An intrabar run ends on its bar: the chart's last bar stays the main run's.\n const lastIndex = intrabarRun ? intrabarRun.lastBarIndex : b.length - 1;\n let out: number[] = [];\n const cache = new Map<Series, number[]>();\n // history buffers by source: the slot of a Series made by the script (matched across incremental runs), or the Series\n const buffers = new Map<unknown, HistoryBuffer>();\n const bufferKey = (src: Series): unknown => incremental.slotOf(src) ?? src;\n let pendingError: { bar: number; barsBack: number } | null = null;\n let idx = 0;\n\n // An incremental run (#196): the block is matched by its order with the previous run; a resumed block starts on the\n // forming bar of the previous run, from its state at the end of the last confirmed bar.\n const run = incremental.active;\n const slot = run ? (run.block < 0 ? run.blockSlot++ : -1) : -1;\n if (run && slot < 0) incremental.nonIncremental('eachBar() inside eachBar()');\n if (run?.mode === 'record') {\n // a variable outside the callback that it changes is not put back by a resumed run: use persist()\n const written = outerWritesOf(own);\n if (written.length) incremental.nonIncremental(`eachBar() callback changes ${written.join(', ')} outside it (use persist())`);\n }\n let start = 0;\n let checkpoint: incremental.BlockCheckpoint | null = null;\n if (run?.mode !== 'resume') out = new Array(b.length).fill(NaN);\n else {\n const prev = run.prev?.blocks[slot];\n if (!prev) incremental.nonIncremental('a new eachBar() block');\n start = run.from;\n // the block's own array of the previous run: its first values are kept in place\n out = prev!.out;\n out.length = b.length;\n for (let i = start; i < b.length; i++) out[i] = NaN;\n checkpoint = prev!.checkpoint;\n // the block that draws puts the registry back to the last confirmed bar\n if (run.prev!.drawingBlock === slot && checkpoint.drawings) restoreDrawingCheckpoint(checkpoint.drawings);\n if (extra) extra.restore(checkpoint.extra);\n for (const [key, state] of checkpoint.buffers) buffers.set(key, { ...state });\n pendingError = checkpoint.pendingError ? { ...checkpoint.pendingError } : null;\n for (const [box, value] of checkpoint.boxes) {\n const ref = run.boxes[box];\n if (!ref) incremental.nonIncremental('a persist() box of the previous run is missing');\n ref!.set(incremental.copyValue(value));\n }\n }\n /** State at the end of the bar just run: the boxes this block owns, the history buffers */\n const takeCheckpoint = (): incremental.BlockCheckpoint => {\n const boxes = new Map<number, unknown>();\n run!.boxes.forEach((ref, box) => {\n if (run!.next.boxOwner[box] === slot) boxes.set(box, incremental.copyValue(ref.get()));\n });\n const kept = new Map<unknown, HistoryBuffer>();\n for (const [key, state] of buffers) kept.set(key, { ...state });\n return {\n boxes,\n buffers: kept,\n pendingError: pendingError ? { ...pendingError } : null,\n drawings: saveDrawingCheckpoint(),\n extra: extra?.save(),\n };\n };\n // the last confirmed bar is before the first bar run (a new run of one bar): its state is the initial one\n if (run && b.length - 2 < start && !checkpoint) checkpoint = takeCheckpoint();\n\n const ctx: BarContext = {\n get i() {\n return idx;\n },\n get n() {\n // the bar count changes with each new bar: a value read from it is not kept by an incremental run (the chart's\n // last bar of the intrabar runs of a backtest does not change)\n if (run && !intrabarRun) incremental.nonIncremental('BarContext.n');\n return lastIndex + 1;\n },\n get time() {\n return b[idx]!.time as number;\n },\n get open() {\n return b[idx]!.open;\n },\n get high() {\n return b[idx]!.high;\n },\n get low() {\n return b[idx]!.low;\n },\n get close() {\n return b[idx]!.close;\n },\n get volume() {\n return b[idx]!.volume ?? NaN;\n },\n get(src: Series, offset: number = 0): number {\n if (offset < 0) throw new RangeError(`c.get(): the offset cannot be negative (${offset} would read a future bar).`);\n if (!src.fullHistory && offset > 0) {\n const k = Math.floor(offset);\n if (k > MAX_BARS_BACK) throw new Error(historyError(idx, k));\n let buffer = buffers.get(bufferKey(src));\n if (!buffer) buffers.set(bufferKey(src), (buffer = { size: HISTORY_START, previous: 0, barMax: 0 }));\n if (k > buffer.barMax) buffer.barMax = k;\n }\n let vals = cache.get(src);\n if (!vals) {\n vals = src.toArray();\n cache.set(src, vals);\n }\n const j = idx - offset;\n return j >= 0 && j < vals.length ? (vals[j] ?? NaN) : NaN;\n },\n prev(offset: number = 1): number {\n const j = idx - Math.max(1, offset);\n return j >= 0 ? out[j]! : NaN;\n },\n };\n const outerBlock = run ? run.block : -1;\n if (run) run.block = slot;\n try {\n for (idx = start; idx < b.length; idx++) {\n if (pendingError && pendingError.bar === idx) throw new Error(historyError(idx, pendingError.barsBack));\n currentBar = idx;\n setDrawingBar(idx, idx === lastIndex, lastIndex);\n const r = fn(ctx);\n out[idx] = typeof r === 'number' ? r : typeof r === 'boolean' ? (r ? 1 : 0) : NaN;\n // grow the history buffers from the largest reference of this bar\n for (const buffer of buffers.values()) {\n const k = buffer.barMax;\n if (k > buffer.size) {\n const next = k - buffer.previous > 1 ? k : Math.round(buffer.size * HISTORY_GROWTH);\n if (next > MAX_BARS_BACK && !pendingError) pendingError = { bar: idx + 1, barsBack: next };\n buffer.size = next;\n }\n buffer.previous = k;\n buffer.barMax = 0;\n }\n // the last confirmed bar (the forming bar is the last one): its state is where the next update starts\n if (run && idx === b.length - 2) checkpoint = takeCheckpoint();\n }\n } finally {\n currentBar = -1;\n setDrawingBar(null);\n if (run) run.block = outerBlock;\n }\n if (run) run.next.blocks[slot] = { out, checkpoint: checkpoint! };\n return Series.fromArray(ctxBars, out);\n}\n\n/** Bar index of the running eachBar() callback, -1 outside eachBar(). */\nlet currentBar = -1;\n\n// \u2500\u2500 Strategy (declaration and strategy.* API; the host supplies the order engine) \u2500\u2500\n\n/** The strategy of the current run; throws when the script did not declare strategy(). */\nfunction strategyRun(caller: string): StrategyRun {\n const run = collector().strategy;\n if (!run) throw new Error(`${caller}: declare the script with strategy() first.`);\n return run;\n}\n\nfunction strategyEngine(caller: string): StrategyEngine {\n const run = strategyRun(caller);\n if (!run.engine) {\n throw new Error(\n `${caller}: no strategy engine; pass it as executeScript(body, bars, inputs, chart, { strategyEngine }).`\n );\n }\n return run.engine;\n}\n\n/** The engine for an order call: order calls run inside strategy.eachBar(), at a bar close. */\nfunction orderEngine(caller: string): StrategyEngine {\n const engine = strategyEngine(caller);\n if (!strategyRun(caller).inLoop) throw new Error(`${caller} must be called inside strategy.eachBar().`);\n return engine;\n}\n\n/** Options without na (NaN) numbers and undefined values: in PineScript an na argument means \"not given\". */\nfunction given<T extends object>(options: T): T {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(options)) {\n if (value === undefined || (typeof value === 'number' && Number.isNaN(value))) continue;\n out[key] = value;\n }\n return out as T;\n}\n\n/** The engine for a `strategy.*` read: the values are per bar, so they are read inside strategy.eachBar(). */\nfunction readEngine(caller: string): StrategyEngine {\n const engine = strategyEngine(caller);\n if (!strategyRun(caller).inLoop) throw new Error(`${caller} must be read inside strategy.eachBar().`);\n return engine;\n}\n\n/** `strategy.*` variables that do not change from bar to bar, readable anywhere in the script. */\nconst STRATEGY_CONSTANT_VARIABLES: ReadonlySet<StrategyVariable> = new Set(['initial_capital', 'account_currency']);\n\nfunction strategyVariable(name: StrategyVariable): number | string {\n const caller = `strategy.${name}`;\n const engine = STRATEGY_CONSTANT_VARIABLES.has(name) ? strategyEngine(caller) : readEngine(caller);\n const value = engine.get(name);\n if (value === undefined) throw new Error(`strategy.${name} is not provided by the strategy engine.`);\n return value;\n}\n\nfunction riskRule(rule: StrategyRiskRule): void {\n if (intrabarRun) return; // declared by the main run\n const engine = strategyEngine(`strategy.risk.${rule.rule}()`);\n if (!engine.risk) throw new Error(`strategy.risk.${rule.rule}() is not provided by the strategy engine.`);\n engine.risk(rule);\n}\n\n/** PineScript `strategy()` declaration: script metadata and strategy properties. */\nfunction declareStrategy(title: string, options: StrategyOptions = {}): void {\n const c = collector();\n declare(c, 'strategy');\n c.title = title;\n c.shortTitle = options.shorttitle;\n c.overlay = options.overlay ?? false;\n c.precision = options.precision;\n c.format = options.format;\n setDrawingLimits({\n line: options.max_lines_count,\n label: options.max_labels_count,\n box: options.max_boxes_count,\n polyline: options.max_polylines_count,\n });\n const properties: StrategyProperties = { ...STRATEGY_DEFAULTS };\n const target = properties as unknown as Record<string, unknown>;\n for (const key of [...Object.keys(STRATEGY_DEFAULTS), 'currency']) {\n const value = (options as Record<string, unknown>)[key];\n if (value !== undefined) target[key] = value;\n }\n const factory = scriptOptions.strategyEngine;\n c.strategy = {\n properties,\n engine: factory?.({ properties, bars: ctxBars.bars, chart: chartCtx }),\n looped: false,\n inLoop: false,\n };\n}\n\n/**\n * Runs the strategy logic once per bar, in order, like {@link eachBar}. On each bar the engine first\n * fills the pending orders (`processBar`), then the callback runs at the bar close (order calls,\n * `strategy.*` variables), then `processClose` runs. A script has one strategy.eachBar() per run.\n * The callback's return values are collected into a Series, as with eachBar().\n */\nfunction strategyEachBar(fn: (c: BarContext) => number | boolean | void): Series {\n const run = strategyRun('strategy.eachBar()');\n const engine = strategyEngine('strategy.eachBar()');\n if (run.looped) throw new Error('strategy.eachBar() runs once per script run.');\n run.looped = true;\n const intrabar = intrabarRun;\n if (intrabar) {\n // Intrabar run: the bars before replay the main run's answers, the bar itself calls the engine (whose\n // orders the host is filling: no processBar / processClose).\n const varipState = varipRun;\n const replayLog: { answers: readonly unknown[]; next: number } = { answers: [], next: 0 };\n const replayed = replayEngine(replayLog);\n return runBlock((c) => {\n const replay = c.i < intrabar.bar;\n if (replay) {\n replayLog.answers = intrabar.recorder.answers[c.i] ?? [];\n replayLog.next = 0;\n }\n run.engine = replay ? replayed : intrabar.engine;\n varipState.mode = replay ? 'replay' : 'live';\n const starts = replay ? intrabar.recorder.varipStarts[c.i] ?? intrabar.recorder.varip : null;\n varipState.scratch = starts ? (starts.length ? [...starts] : NO_VARIP) : null;\n run.inLoop = true;\n try {\n return fn(c);\n } finally {\n run.inLoop = false;\n run.engine = intrabar.engine;\n varipState.mode = 'live';\n varipState.scratch = null;\n }\n }, undefined, fn);\n }\n const recorder = scriptOptions.recorder;\n // an incremental run keeps the engine state at the last confirmed bar: the engine has to save and restore it\n if (incremental.active) {\n if (recorder) incremental.nonIncremental('a strategy with intrabar runs (recorder)');\n if (!engine.save || !engine.restore) incremental.nonIncremental('a strategy engine without save() / restore()');\n }\n const extra: BlockExtra | undefined =\n engine.save && engine.restore ? { save: () => engine.save!(), restore: (s) => engine.restore!(s) } : undefined;\n return runBlock((c) => {\n engine.processBar(c.i);\n if (recorder) {\n recorder.varipStarts[c.i] = [...recorder.varip];\n run.engine = recordingEngine(engine, (recorder.answers[c.i] = []));\n }\n run.inLoop = true;\n try {\n return fn(c);\n } finally {\n run.inLoop = false;\n run.engine = engine;\n engine.processClose(c.i);\n }\n }, extra, fn);\n}\n\n/** The engine of a main run that records its answers (see {@link StrategyRecorder}). */\nfunction recordingEngine(engine: StrategyEngine, log: unknown[]): StrategyEngine {\n const keep = <T>(v: T): T => {\n log.push(v);\n return v;\n };\n return {\n ...forward(engine),\n get: (name) => keep(engine.get(name)),\n openTrade: (index) => keep(engine.openTrade(index)),\n closedTrade: (index) => keep(engine.closedTrade(index)),\n defaultEntryQty: engine.defaultEntryQty ? (price) => keep(engine.defaultEntryQty!(price)) : undefined,\n };\n}\n\n/** An engine that gives back recorded answers in order and drops the order calls (a replayed bar). */\nfunction replayEngine(log: { answers: readonly unknown[]; next: number }): StrategyEngine {\n const next = <T>(): T => log.answers[log.next++] as T;\n const none = (): void => {};\n return {\n processBar: none,\n processClose: none,\n entry: none,\n order: none,\n exit: none,\n close: none,\n close_all: none,\n cancel: none,\n cancel_all: none,\n risk: none,\n get: () => next(),\n openTrade: () => next(),\n closedTrade: () => next(),\n defaultEntryQty: () => next(),\n };\n}\n\n/** The calls of `engine`, bound to it. */\nfunction forward(engine: StrategyEngine): StrategyEngine {\n return {\n processBar: (bar) => engine.processBar(bar),\n processClose: (bar) => engine.processClose(bar),\n entry: (id, direction, options) => engine.entry(id, direction, options),\n order: (id, direction, options) => engine.order(id, direction, options),\n exit: (id, options) => engine.exit(id, options),\n close: (id, options) => engine.close(id, options),\n close_all: (options) => engine.close_all(options),\n cancel: (id) => engine.cancel(id),\n cancel_all: () => engine.cancel_all(),\n risk: engine.risk ? (rule) => engine.risk!(rule) : undefined,\n get: (name) => engine.get(name),\n openTrade: (index) => engine.openTrade(index),\n closedTrade: (index) => engine.closedTrade(index),\n defaultEntryQty: engine.defaultEntryQty ? (price) => engine.defaultEntryQty!(price) : undefined,\n };\n}\n\n/** Numeric `strategy.*` variables, read from the engine (current bar inside strategy.eachBar()). */\nexport type StrategyNumberVariables = { readonly [K in StrategyNumberVariable]: number };\n/** Text `strategy.*` variables, read from the engine. */\nexport type StrategyTextVariables = { readonly [K in StrategyTextVariable]: string };\n\n/** PineScript `strategy`: the `strategy()` declaration and the `strategy.*` namespace. */\nexport type StrategyApi = ((title: string, options?: StrategyOptions) => void) &\n typeof STRATEGY_CONSTANTS &\n StrategyNumberVariables &\n StrategyTextVariables & {\n eachBar: typeof strategyEachBar;\n entry(id: string, direction: StrategyDirection, options?: StrategyEntryOptions): void;\n order(id: string, direction: StrategyDirection, options?: StrategyEntryOptions): void;\n exit(id: string, options?: StrategyExitOptions): void;\n close(id: string, options?: StrategyCloseOptions): void;\n close_all(options?: StrategyCloseAllOptions): void;\n cancel(id: string): void;\n cancel_all(): void;\n /** PineScript `strategy.opentrades.*(index)`: open trade `index` (0 = oldest), undefined when it does not exist. */\n opentrade(index: number): StrategyTrade | undefined;\n /** PineScript `strategy.closedtrades.*(index)`: closed trade `index` (0 = oldest), undefined when it does not exist. */\n closedtrade(index: number): StrategyTrade | undefined;\n default_entry_qty(fill_price: number): number;\n risk: {\n allow_entry_in(direction: StrategyRiskDirection): void;\n max_cons_loss_days(count: number, alert_message?: string): void;\n max_drawdown(value: number, type: StrategyRiskValueType, alert_message?: string): void;\n max_intraday_filled_orders(count: number, alert_message?: string): void;\n max_intraday_loss(value: number, type: StrategyRiskValueType, alert_message?: string): void;\n max_position_size(contracts: number): void;\n };\n };\n\nconst strategyMembers = {\n ...STRATEGY_CONSTANTS,\n eachBar: strategyEachBar,\n entry(id: string, direction: StrategyDirection, options: StrategyEntryOptions = {}): void {\n orderEngine('strategy.entry()').entry(id, direction, given(options));\n },\n order(id: string, direction: StrategyDirection, options: StrategyEntryOptions = {}): void {\n orderEngine('strategy.order()').order(id, direction, given(options));\n },\n exit(id: string, options: StrategyExitOptions = {}): void {\n orderEngine('strategy.exit()').exit(id, given(options));\n },\n close(id: string, options: StrategyCloseOptions = {}): void {\n orderEngine('strategy.close()').close(id, given(options));\n },\n close_all(options: StrategyCloseAllOptions = {}): void {\n orderEngine('strategy.close_all()').close_all(given(options));\n },\n cancel(id: string): void {\n orderEngine('strategy.cancel()').cancel(id);\n },\n cancel_all(): void {\n orderEngine('strategy.cancel_all()').cancel_all();\n },\n opentrade(index: number): StrategyTrade | undefined {\n return readEngine('strategy.opentrade()').openTrade(index);\n },\n closedtrade(index: number): StrategyTrade | undefined {\n return readEngine('strategy.closedtrade()').closedTrade(index);\n },\n default_entry_qty(fill_price: number): number {\n const engine = readEngine('strategy.default_entry_qty()');\n if (!engine.defaultEntryQty) throw new Error('strategy.default_entry_qty() is not provided by the strategy engine.');\n return engine.defaultEntryQty(fill_price);\n },\n risk: {\n allow_entry_in: (direction: StrategyRiskDirection) => riskRule({ rule: 'allow_entry_in', direction }),\n max_cons_loss_days: (count: number, alert_message?: string) =>\n riskRule(given({ rule: 'max_cons_loss_days' as const, count, alert_message })),\n max_drawdown: (value: number, type: StrategyRiskValueType, alert_message?: string) =>\n riskRule(given({ rule: 'max_drawdown' as const, value, type, alert_message })),\n max_intraday_filled_orders: (count: number, alert_message?: string) =>\n riskRule(given({ rule: 'max_intraday_filled_orders' as const, count, alert_message })),\n max_intraday_loss: (value: number, type: StrategyRiskValueType, alert_message?: string) =>\n riskRule(given({ rule: 'max_intraday_loss' as const, value, type, alert_message })),\n max_position_size: (contracts: number) => riskRule({ rule: 'max_position_size', contracts }),\n },\n};\n\nconst variableGetters: PropertyDescriptorMap = {};\nfor (const name of [...STRATEGY_NUMBER_VARIABLES, ...STRATEGY_TEXT_VARIABLES]) {\n variableGetters[name] = { get: () => strategyVariable(name), enumerable: true };\n}\n\n/**\n * PineScript `strategy`: call it to declare a strategy, and use its members as the `strategy.*` namespace.\n * OakScriptJS does not fill orders: the host passes an engine in `executeScript(..., { strategyEngine })`,\n * and the order calls and `strategy.*` variables are forwarded to it.\n *\n * ```typescript\n * strategy('MA Cross', { initial_capital: 10000, default_qty_type: strategy.percent_of_equity, default_qty_value: 100 });\n * const up = ta.crossover(ta.sma(close, 9), ta.sma(close, 21));\n * strategy.eachBar((c) => {\n * if (c.get(up) && strategy.position_size === 0) {\n * strategy.entry('L', strategy.long);\n * strategy.exit('X', { from_entry: 'L', stop: c.close * 0.95, limit: c.close * 1.15 });\n * }\n * });\n * ```\n */\nexport const strategy: StrategyNamespace = Object.defineProperties(\n Object.assign((title: string, options?: StrategyOptions) => declareStrategy(title, options), strategyMembers),\n variableGetters\n) as StrategyApi;\nsameKeys<StrategyApi, StrategyNamespace>(true);\nsameKeys<StrategyApi['risk'], StrategyNamespace['risk']>(true);\n\n/** Types of chart PineScript tells apart (`chart.is_*`); every other type is 'standard'. */\nexport type ChartType = 'standard' | 'heikinashi' | 'renko' | 'kagi' | 'linebreak' | 'pnf' | 'range';\n\n// \u2500\u2500 Chart context (issue #100) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * What the caller knows about the loaded bars. PineScript reads these values from the chart and\n * the symbol; nothing is fetched here. A script that needs a value the caller did not give throws.\n */\nexport interface ChartContext {\n /** Chart timeframe: \"5\", \"60\", \"1D\", \"1W\"... (PineScript `timeframe.period`) */\n timeframe?: string;\n /** Exchange time zone: \"America/New_York\", \"Etc/UTC\"... (PineScript `syminfo.timezone`) */\n timezone?: string;\n /** Session type of the bars (PineScript `syminfo.session`); default \"regular\" */\n sessionType?: 'regular' | 'extended';\n /**\n * Session of the loaded bars in the symbol session format: hours (\"0930-1600\", \"1700-1600\", \"24x7\"),\n * corrections (early closes, days off) and holidays. Needed by `time(tf)`, `time_close`,\n * `timeframe.change`, `time_tradingday`, `session.*` and the default anchor of `ta.vwap`.\n */\n session?: SessionSpec | string;\n /** Regular trading hours when the bars include extended hours (default: `session`); holidays default to `session`'s */\n regularSession?: SessionSpec | string;\n /** Chart symbol as PineScript `syminfo.tickerid` (e.g. \"NASDAQ:AAPL\"); needed by `request.security(syminfo.tickerid, ...)` */\n tickerid?: string;\n /** Unit of `Bar.time`: 's' (default, as lightweight-charts) or 'ms'. PineScript times are in ms. */\n timeUnit?: 's' | 'ms';\n /**\n * Minimum price move of the symbol (PineScript `syminfo.mintick`), e.g. 0.01; used by `math.round_to_mintick` and\n * `format.mintick`. Default: `minmove / pricescale` when both are given\n */\n mintick?: number;\n /**\n * PineScript `syminfo.minmove` and `syminfo.pricescale` (mintick = minmove / pricescale). Default: from `mintick`,\n * with pricescale 10^(its decimals) (0.25 is 25 / 100). Pass them for a symbol priced in fractions (1 / 32):\n * `format.mintick` shows floor(log10(pricescale)) decimals\n */\n minmove?: number;\n pricescale?: number;\n /** Currency value of one point of price move for one contract (PineScript `syminfo.pointvalue`); 1 for stocks */\n pointvalue?: number;\n /** Smallest tradable quantity (PineScript `syminfo.mincontract`); 1 for whole shares */\n mincontract?: number;\n /** Symbol type (PineScript `syminfo.type`): \"stock\", \"crypto\", \"forex\", \"futures\", \"index\", \"fund\"... */\n symbolType?: string;\n /** Currency of the symbol (PineScript `syminfo.currency`), e.g. \"USD\" */\n currency?: string;\n /**\n * Base currency of the symbol (PineScript `syminfo.basecurrency`): \"BTC\" for BITSTAMP:BTCUSD, BINANCE:BTCUSDT.P and\n * CME:BTC1!, \"EUR\" for FX:EURUSD, \"\" for a stock, an index or CME_MINI:ES1! (#180).\n *\n * The symbol fields below, like this one: a value; null when the symbol has none (PineScript gives na: \"\" for a\n * text, which `na()` takes as na, NaN for a number); left out when the host does not know it (reading it throws).\n */\n basecurrency?: string | null;\n /**\n * Root of the symbol (PineScript `syminfo.root`): \"BTC\" for CME:BTC1!, \"ES\" for CME_MINI:ES1!, \"AAPL\" for\n * NASDAQ:AAPL (#180). Default: the ticker, without the \"1!\" of a continuous future or the month code and year of a\n * contract (\"ESZ2026\" of a `symbolType` \"futures\").\n */\n root?: string | null;\n /** Description of the symbol (PineScript `syminfo.description`): \"Apple Inc.\" for NASDAQ:AAPL, \"Bitcoin / U.S. dollar\" for BITSTAMP:BTCUSD (#184) */\n description?: string | null;\n /** Prefix of the ticker id (PineScript `syminfo.prefix`), default: the part of `tickerid` before \":\" */\n prefix?: string | null;\n /** Ticker without its prefix (PineScript `syminfo.ticker`), default: the part of `tickerid` after \":\" */\n ticker?: string;\n /** The chart's own symbol (PineScript `syminfo.main_tickerid`, the same inside `request.security`); default `tickerid` */\n mainTickerid?: string;\n /** The chart's own timeframe (`timeframe.main_period`, the same inside `request.security`); default `timeframe` */\n mainTimeframe?: string;\n /** Two-letter code of the country the symbol trades in (PineScript `syminfo.country`): \"US\", \"IN\" */\n country?: string | null;\n /** Contract a continuous future stands for (PineScript `syminfo.current_contract`): \"ESZ2026\" for CME_MINI:ES1! */\n currentContract?: string | null;\n /** Last trading day of a future's contract, in ms (PineScript `syminfo.expiration_date`) */\n expirationDate?: number | null;\n /** PineScript `syminfo.sector` and `syminfo.industry` of a company */\n sector?: string | null;\n industry?: string | null;\n /** PineScript `syminfo.isin`: \"US0378331005\" for NASDAQ:AAPL */\n isin?: string | null;\n /** Unit of the volume (PineScript `syminfo.volumetype`): \"base\" (crypto: in the base currency), \"quote\", \"tick\", \"n/a\" */\n volumetype?: string | null;\n /** PineScript `syminfo.employees`, `syminfo.shareholders`, `syminfo.shares_outstanding_total` / `_float` */\n employees?: number | null;\n shareholders?: number | null;\n sharesOutstandingTotal?: number | null;\n sharesOutstandingFloat?: number | null;\n /** Analysts' ratings (PineScript `syminfo.recommendations_*`; `date` in ms) */\n recommendations?: SymbolRecommendations | null;\n /** Analysts' price targets (PineScript `syminfo.target_price_*`; `date` in ms) */\n targetPrice?: SymbolTargetPrice | null;\n /**\n * Dividends, splits and earnings of a symbol (PineScript `request.dividends`, `request.splits`, `request.earnings`,\n * `dividends.future_*`, `earnings.future_*`). Return undefined when they are not loaded: the run then ends with a\n * {@link MissingSymbolDataError} whose request has `events: true`. Return {} for a symbol without any.\n */\n events?: (symbol: string) => SymbolEvents | undefined;\n /** Chart foreground colour (PineScript `chart.fg_color`), e.g. \"#DBDBDB\" on a dark chart */\n foregroundColor?: string;\n /** Chart background colour (PineScript `chart.bg_color`), e.g. \"#0F0F0F\" on a dark chart */\n backgroundColor?: string;\n /**\n * Times (ms) of the first and the last bar in view (PineScript `chart.left_visible_bar_time` and\n * `chart.right_visible_bar_time`); default: the first and the last bar. A script that reads them\n * ({@link ScriptRunResult.usesVisibleRange}) has to be calculated again when they change.\n */\n leftVisibleBarTime?: number;\n rightVisibleBarTime?: number;\n /** Type of the chart (PineScript `chart.is_standard`, `chart.is_heikinashi`...); default 'standard' */\n chartType?: ChartType;\n /** Current time in ms (PineScript `timenow`); default: the clock of the computer at the start of the run */\n now?: number;\n /**\n * The last bar is closed (`barstate.isconfirmed` on the last bar). Default false: PineScript treats the last bar\n * of the data as not confirmed until the data feed closes it.\n */\n lastBarConfirmed?: boolean;\n /** The last bar receives live updates (`barstate.isrealtime`); default false (a calculation on history). */\n realtime?: boolean;\n /** On a realtime last bar: this run is the first update of the bar (`barstate.isnew`); default true. */\n lastBarNew?: boolean;\n /**\n * Bars of another symbol for `request.security(symbol, timeframe, ...)` (#179): the bars of `symbol` (the ticker id\n * as written in the script, e.g. \"NASDAQ:MSFT\") on `timeframe` (the chart timeframe for \"\"), oldest first, times in\n * `timeUnit`. Return undefined when they are not loaded: the run then ends with a {@link MissingSymbolDataError}\n * that lists every request, so the host can load them and run again. Return [] for a symbol that does not exist.\n */\n bars?: (symbol: string, timeframe: string) => Bar[] | undefined;\n /**\n * Calendar and properties of another symbol: its time zone and session give the close times and trading days that\n * `request.security` merges on (#179), and the other fields its `syminfo.*` inside the expression.\n */\n symbolInfo?: (symbol: string) => SymbolInfo | undefined;\n /**\n * Ticker of a seed data series for `request.seed(source, symbol, ...)` (#205), whose bars then come from\n * {@link bars} like any other symbol. Default: `\"<SOURCE>:<SYMBOL>\"` upper-cased.\n */\n seedSymbol?: (source: string, symbol: string) => string;\n}\n\n/** Calendar and properties of a symbol, as in {@link ChartContext}. */\nexport type SymbolInfo = Pick<\n ChartContext,\n | 'timezone'\n | 'session'\n | 'regularSession'\n | 'mintick'\n | 'minmove'\n | 'pricescale'\n | 'pointvalue'\n | 'mincontract'\n | 'symbolType'\n | 'currency'\n | 'basecurrency'\n | 'root'\n | 'description'\n | 'prefix'\n | 'ticker'\n | 'country'\n | 'currentContract'\n | 'expirationDate'\n | 'sector'\n | 'industry'\n | 'isin'\n | 'volumetype'\n | 'employees'\n | 'shareholders'\n | 'sharesOutstandingTotal'\n | 'sharesOutstandingFloat'\n | 'recommendations'\n | 'targetPrice'\n>;\n\n/** The symbol fields a {@link SymbolInfo} gives to `syminfo.*` inside `request.security`. */\nconst SYMBOL_INFO_KEYS = [\n 'timezone', 'session', 'regularSession', 'mintick', 'minmove', 'pricescale', 'pointvalue', 'mincontract', 'symbolType',\n 'currency', 'basecurrency', 'root', 'description', 'prefix', 'ticker', 'country', 'currentContract', 'expirationDate',\n 'sector', 'industry', 'isin', 'volumetype', 'employees', 'shareholders', 'sharesOutstandingTotal',\n 'sharesOutstandingFloat', 'recommendations', 'targetPrice',\n] as const satisfies readonly (keyof SymbolInfo)[];\n\n/** Analysts' ratings of a symbol: counts of each rating, and the date of the count (ms). */\nexport interface SymbolRecommendations {\n buy: number;\n buy_strong: number;\n hold: number;\n sell: number;\n sell_strong: number;\n total: number;\n date: number;\n}\n\n/** Analysts' price targets of a symbol, their number and the date of the figures (ms). */\nexport interface SymbolTargetPrice {\n average: number;\n high: number;\n low: number;\n median: number;\n estimates: number;\n date: number;\n}\n\n/**\n * A dividend: `time` the ex-date (ms; 00:00 UTC of the day, as PineScript's dividends are stamped), the amount per\n * share as declared (not adjusted for later splits), net and gross of withholding tax (gross defaults to net).\n */\nexport interface DividendEvent {\n time: number;\n net: number;\n gross?: number;\n /** Payment date (ms) */\n payDate?: number | null;\n}\n\n/** A split from `denominator` shares to `numerator` (4 and 1 for a 4-for-1 split); `time` its date (ms, 00:00 UTC). */\nexport interface SplitEvent {\n time: number;\n numerator: number;\n denominator: number;\n}\n\n/**\n * An earnings release: `time` when it was published (ms; a release after the close is after the session's close). The\n * values per share are adjusted for later splits, as PineScript gives them. A value the host does not have is left\n * out; a script that asks for it then stops with an error.\n */\nexport interface EarningsEvent {\n time: number;\n /** Reported earnings per share (`earnings.actual`), the analysts' estimate (`earnings.estimate`), standardized\n * earnings per share (`earnings.standardized`) */\n actual?: number | null;\n estimate?: number | null;\n standardized?: number | null;\n /** Estimated revenue (`earnings.future_revenue`) and the end of the fiscal period (ms) */\n revenueEstimate?: number | null;\n periodEnd?: number | null;\n}\n\n/** Events of a symbol, oldest first. */\nexport interface SymbolEvents {\n dividends?: DividendEvent[];\n splits?: SplitEvent[];\n earnings?: EarningsEvent[];\n /**\n * The lists hold the announced events still to come (`dividends.future_*`, `earnings.future_*` read them): without\n * it the future values are not known and reading them throws.\n */\n future?: { dividends?: boolean; earnings?: boolean };\n}\n\n/**\n * A request of `request.security` for another symbol whose bars the host has not given, or (`events`) of\n * `request.dividends` / `request.splits` / `request.earnings` for a symbol whose events it has not given.\n */\nexport interface SymbolDataRequest {\n symbol: string;\n timeframe: string;\n events?: boolean;\n}\n\n/**\n * Thrown by `executeScript` when `request.security` asked for bars of another symbol that `ChartContext.bars` did not\n * give (#179). `requests` lists them all, once each: load them, then run the script again.\n */\nexport class MissingSymbolDataError extends Error {\n constructor(readonly requests: SymbolDataRequest[]) {\n const bars = requests.filter((r) => !r.events);\n const events = requests.filter((r) => r.events);\n super(\n [\n bars.length ? `request.security needs the bars of ${bars.map((r) => `${r.symbol} (${r.timeframe})`).join(', ')}: pass them with ChartContext.bars.` : '',\n events.length ? `The script needs the events of ${events.map((r) => r.symbol).join(', ')}: pass them with ChartContext.events.` : '',\n ].filter(Boolean).join(' ')\n );\n this.name = 'MissingSymbolDataError';\n }\n}\n\n/** Requests of other symbols without bars in the current run. */\nlet missingSymbols: SymbolDataRequest[] = [];\n\nlet chartCtx: ChartContext = {};\n\nfunction chartTimeframe(): timeframeCore.TimeframeInfo {\n collector();\n if (!chartCtx.timeframe) {\n throw new Error('The chart timeframe is not known: pass it as executeScript(body, bars, inputs, { timeframe }).');\n }\n return timeframeCore.info(chartCtx.timeframe);\n}\n\nfunction exchangeTimezone(): string {\n collector();\n if (!chartCtx.timezone) {\n throw new Error('The exchange time zone is not known: pass it as executeScript(body, bars, inputs, { timezone }).');\n }\n return chartCtx.timezone;\n}\n\n/**\n * PineScript `timeframe.*`: the chart timeframe variables (from the chart context), and\n * `in_seconds(timeframe?)`, `from_seconds(seconds)`.\n */\nexport const timeframe: TimeframeNamespace = {\n ...timeframeCore,\n get period(): string {\n return chartTimeframe().period;\n },\n get main_period(): string {\n const main = chartCtx.mainTimeframe;\n return main ? timeframeCore.info(main).period : chartTimeframe().period;\n },\n get multiplier(): number {\n return chartTimeframe().multiplier;\n },\n get isintraday(): boolean {\n return chartTimeframe().isintraday;\n },\n get isdaily(): boolean {\n return chartTimeframe().isdaily;\n },\n get isweekly(): boolean {\n return chartTimeframe().isweekly;\n },\n get ismonthly(): boolean {\n return chartTimeframe().ismonthly;\n },\n get isminutes(): boolean {\n return chartTimeframe().isminutes;\n },\n get isseconds(): boolean {\n return chartTimeframe().isseconds;\n },\n get isticks(): boolean {\n return chartTimeframe().isticks;\n },\n get isdwm(): boolean {\n return chartTimeframe().isdwm;\n },\n /** PineScript `timeframe.change(tf)`: 1 on bars that open a new `tf` period (0 on the first bar). */\n change(tf: string): Series {\n return changeOf(tf || chartTimeframe().period);\n },\n /** Seconds in `timeframe`; without it (or with \"\") the chart timeframe, as in PineScript. */\n in_seconds(tf?: string): number {\n return timeframeCore.in_seconds(tf === undefined || tf === '' ? chartTimeframe().period : tf);\n },\n};\n\n/** A symbol property that the host passes in the chart context. */\nfunction symbolProperty(key: 'mintick' | 'pointvalue' | 'mincontract'): number {\n collector();\n const value = chartCtx[key];\n if (value === undefined) {\n if (key === 'mintick' && chartCtx.minmove !== undefined && chartCtx.pricescale !== undefined) {\n return chartCtx.minmove / chartCtx.pricescale;\n }\n throw new Error(`syminfo.${key} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);\n }\n return value;\n}\n\n/** A text value of the chart or the symbol that the host passes in the chart context; null (none) is \"\". */\nfunction chartText(\n key:\n | 'symbolType'\n | 'currency'\n | 'basecurrency'\n | 'root'\n | 'description'\n | 'foregroundColor'\n | 'backgroundColor'\n | 'prefix'\n | 'country'\n | 'currentContract'\n | 'sector'\n | 'industry'\n | 'isin'\n | 'volumetype',\n name: string\n): string {\n collector();\n const value = chartCtx[key];\n if (value === undefined) {\n throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);\n }\n // PineScript's na text is \"\" (`na(\"\")` is true)\n return value ?? '';\n}\n\n/** A number of the symbol that the host passes in the chart context; null (none) is na. */\nfunction symbolNumber(\n key: 'expirationDate' | 'employees' | 'shareholders' | 'sharesOutstandingTotal' | 'sharesOutstandingFloat',\n name: string\n): number {\n collector();\n const value = chartCtx[key];\n if (value === undefined) {\n throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);\n }\n return value ?? NaN;\n}\n\n/** A value of the analysts' figures of the symbol (`recommendations`, `targetPrice`); null (none) is na. */\nfunction analystNumber<K extends 'recommendations' | 'targetPrice'>(\n key: K,\n field: keyof NonNullable<ChartContext[K]>,\n name: string\n): number {\n collector();\n const group = chartCtx[key];\n if (group === undefined) {\n throw new Error(`${name} is not known: pass it as executeScript(body, bars, inputs, { ${key} }).`);\n }\n return group === null ? NaN : ((group as unknown as Record<string, number>)[field as string] ?? NaN);\n}\n\n/** The ticker id of the chart (or of the symbol of `request.security`); throws when not known. */\nfunction chartTickerid(): string {\n collector();\n if (!chartCtx.tickerid) {\n throw new Error('The chart symbol is not known: pass it as executeScript(body, bars, inputs, { tickerid }).');\n }\n return chartCtx.tickerid;\n}\n\n/** A ticker id cut at its prefix: [\"NASDAQ\", \"AAPL\"], [\"\", \"AAPL\"] without one. */\nfunction splitTickerid(tickerid: string): [string, string] {\n const at = tickerid.indexOf(':');\n return at < 0 ? ['', tickerid] : [tickerid.slice(0, at), tickerid.slice(at + 1)];\n}\n\n/** Month codes of futures contracts (F = January ... Z = December). */\nconst CONTRACT_SUFFIX = /^(.+?)[FGHJKMNQUVXZ](\\d{4}|\\d{2})$/;\n\n/** Root of a ticker: without the \"1!\" of a continuous future, or the month code and year of a future's contract. */\nfunction tickerRoot(ticker: string, symbolType: string | undefined): string {\n const continuous = /^(.+?)\\d+!$/.exec(ticker);\n if (continuous) return continuous[1]!;\n const contract = symbolType === 'futures' ? CONTRACT_SUFFIX.exec(ticker) : null;\n return contract ? contract[1]! : ticker;\n}\n\n/** A visible range value: the chart context's, else the time of bar `index` (NaN without bars). */\nfunction visibleBarTime(value: number | undefined, index: number): number {\n collector().usesVisibleRange = true;\n if (value !== undefined) return value;\n const bar = ctxBars.bars[index];\n return bar ? barTime(bar) : NaN;\n}\n\nfunction chartTypeIs(type: ChartType): boolean {\n collector();\n return (chartCtx.chartType ?? 'standard') === type;\n}\n\n/** `[minmove, pricescale]` of the chart symbol: from the chart context, else from its mintick. */\nfunction symbolScale(): [number, number] {\n collector();\n const { minmove, pricescale } = chartCtx;\n if (minmove !== undefined && pricescale !== undefined) return [minmove, pricescale];\n const [move, scale] = tickScale(symbolProperty('mintick'), pricescale);\n return [minmove ?? move, scale];\n}\n\n/**\n * PineScript `syminfo.*`, from the chart context (inside `request.security`, the requested symbol's). A field the\n * symbol has none of is na (\"\" for a text); a field the host did not give throws.\n */\nexport const syminfo: SyminfoNamespace = {\n get mintick(): number {\n return symbolProperty('mintick');\n },\n get minmove(): number {\n return symbolScale()[0];\n },\n get pricescale(): number {\n return symbolScale()[1];\n },\n get pointvalue(): number {\n return symbolProperty('pointvalue');\n },\n get mincontract(): number {\n return symbolProperty('mincontract');\n },\n get timezone(): string {\n return exchangeTimezone();\n },\n get tickerid(): string {\n return chartTickerid();\n },\n get main_tickerid(): string {\n const id = chartTickerid();\n return chartCtx.mainTickerid ?? id;\n },\n get ticker(): string {\n const id = chartTickerid();\n return chartCtx.ticker ?? splitTickerid(id)[1];\n },\n get prefix(): string {\n const id = chartTickerid();\n return chartCtx.prefix === undefined ? splitTickerid(id)[0] : (chartCtx.prefix ?? '');\n },\n get session(): string {\n collector();\n return chartCtx.sessionType ?? 'regular';\n },\n get type(): string {\n return chartText('symbolType', 'syminfo.type');\n },\n get currency(): string {\n return chartText('currency', 'syminfo.currency');\n },\n get basecurrency(): string {\n return chartText('basecurrency', 'syminfo.basecurrency');\n },\n get root(): string {\n if (chartCtx.root !== undefined) return chartText('root', 'syminfo.root');\n return tickerRoot(syminfo.ticker, chartCtx.symbolType);\n },\n get description(): string {\n return chartText('description', 'syminfo.description');\n },\n get country(): string {\n return chartText('country', 'syminfo.country');\n },\n get current_contract(): string {\n return chartText('currentContract', 'syminfo.current_contract');\n },\n get expiration_date(): number {\n return symbolNumber('expirationDate', 'syminfo.expiration_date');\n },\n get sector(): string {\n return chartText('sector', 'syminfo.sector');\n },\n get industry(): string {\n return chartText('industry', 'syminfo.industry');\n },\n get isin(): string {\n return chartText('isin', 'syminfo.isin');\n },\n get volumetype(): string {\n return chartText('volumetype', 'syminfo.volumetype');\n },\n get employees(): number {\n return symbolNumber('employees', 'syminfo.employees');\n },\n get shareholders(): number {\n return symbolNumber('shareholders', 'syminfo.shareholders');\n },\n get shares_outstanding_total(): number {\n return symbolNumber('sharesOutstandingTotal', 'syminfo.shares_outstanding_total');\n },\n get shares_outstanding_float(): number {\n return symbolNumber('sharesOutstandingFloat', 'syminfo.shares_outstanding_float');\n },\n get recommendations_buy(): number {\n return analystNumber('recommendations', 'buy', 'syminfo.recommendations_buy');\n },\n get recommendations_buy_strong(): number {\n return analystNumber('recommendations', 'buy_strong', 'syminfo.recommendations_buy_strong');\n },\n get recommendations_hold(): number {\n return analystNumber('recommendations', 'hold', 'syminfo.recommendations_hold');\n },\n get recommendations_sell(): number {\n return analystNumber('recommendations', 'sell', 'syminfo.recommendations_sell');\n },\n get recommendations_sell_strong(): number {\n return analystNumber('recommendations', 'sell_strong', 'syminfo.recommendations_sell_strong');\n },\n get recommendations_total(): number {\n return analystNumber('recommendations', 'total', 'syminfo.recommendations_total');\n },\n get recommendations_date(): number {\n return analystNumber('recommendations', 'date', 'syminfo.recommendations_date');\n },\n get target_price_average(): number {\n return analystNumber('targetPrice', 'average', 'syminfo.target_price_average');\n },\n get target_price_high(): number {\n return analystNumber('targetPrice', 'high', 'syminfo.target_price_high');\n },\n get target_price_low(): number {\n return analystNumber('targetPrice', 'low', 'syminfo.target_price_low');\n },\n get target_price_median(): number {\n return analystNumber('targetPrice', 'median', 'syminfo.target_price_median');\n },\n get target_price_estimates(): number {\n return analystNumber('targetPrice', 'estimates', 'syminfo.target_price_estimates');\n },\n get target_price_date(): number {\n return analystNumber('targetPrice', 'date', 'syminfo.target_price_date');\n },\n};\n\n/** A calendar function: `(time, timezone?)` on a UNIX time or on a Series of times. */\ninterface CalendarFunction {\n /**\n * The calendar field (year, month, day, hour...) of a time.\n * @param time - A time in UNIX milliseconds.\n * @param timezone - Time zone to read the time in: \"America/New_York\", \"UTC+2\"... Default: the exchange's.\n * @returns The calendar field of that time.\n */\n (time: number, timezone?: string): number;\n /**\n * The calendar field (year, month, day, hour...) of each time of a Series, e.g. `year(time)`.\n * @param time - A Series of times in UNIX milliseconds, e.g. `time`.\n * @param timezone - Time zone to read the times in: \"America/New_York\", \"UTC+2\"... Default: the exchange's.\n * @returns Series of the calendar field of each time.\n */\n (time: Series, timezone?: string): Series;\n}\n\nfunction calendar(fn: (time: number, timezone: string) => number): CalendarFunction {\n return ((time: number | Series, timezone?: string) => {\n const tz = timezone ?? exchangeTimezone();\n return time instanceof Series ? Series.fromArray(ctxBars, time.toArray().map((t) => fn(t, tz))) : fn(time, tz);\n }) as CalendarFunction;\n}\n\n/**\n * The year of a time (2025...). Works on one time or on a Series of times (`year(time)` gives the value of each bar).\n * @example\n * ```js\n * const newYear = year(time).neq(year(time).offset(1));\n * bgcolor(color.when(newYear, color.new(color.blue, 80)));\n * ```\n */\nexport const year: CalendarFunction = calendar(timeCore.year);\n/**\n * The month of a time, 1 (January) to 12. Works on one time or on a Series of times (`month(time)` gives the value of each bar).\n * @example\n * ```js\n * const january = month(time).eq(1);\n * bgcolor(color.when(january, color.new(color.teal, 85)));\n * ```\n */\nexport const month: CalendarFunction = calendar(timeCore.month);\n/**\n * The week of the year of a time, 1 to 53. Works on one time or on a Series of times (`weekofyear(time)` gives the value of each bar).\n * @example\n * ```js\n * plot(weekofyear(time), \"Week\");\n * ```\n */\nexport const weekofyear: CalendarFunction = calendar(timeCore.weekofyear);\n/**\n * The day of the month of a time, 1 to 31. Works on one time or on a Series of times (`dayofmonth(time)` gives the value of each bar).\n * @example\n * ```js\n * plot(dayofmonth(time, \"UTC\"), \"Day of month\");\n * ```\n */\nexport const dayofmonth: CalendarFunction = calendar(timeCore.dayofmonth);\n/**\n * The day of the week of a time, 1 (Sunday) to 7 (Saturday), on one time or a Series of times; compare it with the\n * `dayofweek.monday`... constants.\n * @example\n * ```js\n * const monday = dayofweek(time).eq(dayofweek.monday);\n * bgcolor(color.when(monday, color.new(color.gray, 90)));\n * ```\n */\nexport const dayofweek: CalendarFunction & typeof pineConstants.daysOfWeek = Object.assign(calendar(timeCore.dayofweek), pineConstants.daysOfWeek);\n/**\n * The hour of a time, 0 to 23. Works on one time or on a Series of times (`hour(time)` gives the value of each bar).\n * @example\n * ```js\n * const morning = hour(time).lt(12);\n * bgcolor(color.when(morning, color.new(color.orange, 90)));\n * ```\n */\nexport const hour: CalendarFunction = calendar(timeCore.hour);\n/**\n * The minute of a time, 0 to 59. Works on one time or on a Series of times (`minute(time)` gives the value of each bar).\n * @example\n * ```js\n * plot(minute(time), \"Minute\");\n * ```\n */\nexport const minute: CalendarFunction = calendar(timeCore.minute);\n/**\n * The second of a time, 0 to 59. Works on one time or on a Series of times (`second(time)` gives the value of each bar).\n * @example\n * ```js\n * plot(second(time), \"Second\");\n * ```\n */\nexport const second: CalendarFunction = calendar(timeCore.second);\n\n/**\n * The UNIX time (milliseconds) of a date written as text.\n * @param dateString - A date such as \"2024-03-15\", \"2024-03-15T09:30\" or \"15 Mar 2024 09:30 GMT+1\"; without a time\n * zone it is UTC.\n * @returns The time in UNIX milliseconds.\n * @example\n * ```js\n * const start = timestamp(\"2024-01-01\");\n * bgcolor(color.when(time.gte(start), color.new(color.green, 92)));\n * ```\n */\nexport function timestamp(dateString: string): number;\n/**\n * The UNIX time (milliseconds) of a date and time in a time zone.\n * @param timezone - Time zone: \"America/New_York\", \"UTC+2\"...\n * @param year - Year, e.g. 2024.\n * @param month - Month, 1 to 12.\n * @param day - Day of the month, 1 to 31.\n * @param hour - Hour, 0 to 23. Default: 0.\n * @param minute - Minute. Default: 0.\n * @param second - Second. Default: 0.\n * @returns The time in UNIX milliseconds.\n * @example\n * ```js\n * const open = timestamp(\"America/New_York\", 2024, 3, 15, 9, 30);\n * ```\n */\nexport function timestamp(\n timezone: string,\n year: number,\n month: number,\n day: number,\n hour?: number,\n minute?: number,\n second?: number\n): number;\n/**\n * The UNIX time (milliseconds) of a date and time in the exchange's time zone.\n * @param year - Year, e.g. 2024.\n * @param month - Month, 1 to 12.\n * @param day - Day of the month, 1 to 31.\n * @param hour - Hour, 0 to 23. Default: 0.\n * @param minute - Minute. Default: 0.\n * @param second - Second. Default: 0.\n * @returns The time in UNIX milliseconds.\n * @example\n * ```js\n * const from = timestamp(2024, 1, 1);\n * plotshape(time.eq(from), \"Start\");\n * ```\n */\nexport function timestamp(year: number, month: number, day: number, hour?: number, minute?: number, second?: number): number;\nexport function timestamp(first: string | number, ...rest: Array<number | undefined>): number {\n if (typeof first === 'number') {\n const [m, d, h, mi, s] = rest as [number, number, number?, number?, number?];\n return timeCore.timestamp(exchangeTimezone(), first, m, d, h, mi, s);\n }\n if (rest.length === 0) return timeCore.timestamp(first);\n const [y, m, d, h, mi, s] = rest as [number, number, number, number?, number?, number?];\n return timeCore.timestamp(first, y, m, d, h, mi, s);\n}\n\n/**\n * Whether a time is inside a session (trading hours).\n * @param time - A time in UNIX milliseconds, e.g. `c.time` in `eachBar()`.\n * @param session - Session hours and days: \"0930-1600\", \"0930-1600:23456\" (Monday to Friday), \"1800-0500\" (overnight).\n * @param timezone - Time zone of the session hours. Default: the exchange's.\n * @returns true when the time is in the session.\n * @example\n * ```js\n * const regular = eachBar((c) => inSession(c.time, \"0930-1600\"));\n * bgcolor(color.when(regular, color.new(color.blue, 92)));\n * ```\n */\nexport function inSession(time: number, session: string, timezone?: string): boolean {\n return timeCore.inSession(time, session, timezone ?? exchangeTimezone());\n}\n\n/**\n * Text functions: `str.tostring` (a number as text), `str.format` (a pattern with values), `str.format_time` (a date),\n * search, replace, split, case... `str.format_time` and the dates of `str.format` use the exchange's time zone by\n * default.\n * @example\n * ```js\n * eachBar((c) => {\n * if (barstate.islast) log.info(str.format(\"Close {0} at {1}\", c.get(close), str.format_time(c.get(time), \"HH:mm\")));\n * });\n * ```\n */\nexport const str: typeof strCore = strictNamespace('str', {\n ...strCore,\n // format.mintick uses the chart symbol's tick and price scale (syminfo.mintick, syminfo.pricescale)\n tostring: ((value: unknown, format?: string, mintick?: number, pricescale?: number) =>\n format === 'mintick' && mintick === undefined\n ? strCore.tostring(value as never, format, syminfo.mintick, pricescale ?? syminfo.pricescale)\n : strCore.tostring(value as never, format, mintick, pricescale)) as typeof strCore.tostring,\n // the exchange time zone by default; the documentation is the library function's\n format_time: ((time: number, format: string = \"yyyy-MM-dd'T'HH:mm:ssZ\", timezone?: string): string =>\n strCore.format_time(time, format, timezone ?? exchangeTimezone())) as typeof strCore.format_time,\n format: ((pattern: string, ...args: unknown[]): string => formatMessage(pattern, args, exchangeTimezone)) as typeof strCore.format,\n});\n\n// \u2500\u2500 Session values (issue #100) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Bar time in ms (PineScript `time`). */\nfunction barTime(bar: Bar): number {\n return (bar.time as number) * (chartCtx.timeUnit === 'ms' ? 1 : 1000);\n}\n\nconst toSpec = (s: SessionSpec | string): SessionSpec => (typeof s === 'string' ? { session: s } : s);\n\nlet sessionCache: { ctx: ChartContext; bars: SessionBars; regular: SessionBars } | null = null;\n\n/** Session calendars of the run (loaded bars and regular hours), built from the chart context. */\nfunction sessionBars(): { bars: SessionBars; regular: SessionBars } {\n const tz = exchangeTimezone();\n const tf = chartTimeframe().period;\n if (!chartCtx.session) {\n throw new Error('The session is not known: pass it as executeScript(body, bars, inputs, { session }).');\n }\n if (sessionCache?.ctx !== chartCtx) {\n const loaded = toSpec(chartCtx.session);\n const regular = chartCtx.regularSession ? toSpec(chartCtx.regularSession) : loaded;\n sessionCache = {\n ctx: chartCtx,\n bars: new SessionBars(new TradingCalendar(tz, loaded), tf),\n regular: new SessionBars(new TradingCalendar(tz, { holidays: loaded.holidays, ...regular }), tf),\n };\n }\n return sessionCache;\n}\n\nfunction perBar(fn: (t: number, i: number, times: number[]) => number): Series {\n const times = ctxBars.bars.map(barTime);\n return Series.fromArray(ctxBars, times.map((t, i) => fn(t, i, times)));\n}\n\n/** A Series that can also be called, like PineScript's `time` (variable) and `time(...)` (function). */\nfunction callableSeries<F extends (...args: never[]) => Series>(series: Series, fn: F): Series & F {\n Object.setPrototypeOf(fn, Series.prototype);\n Object.assign(fn, series);\n return fn as Series & F;\n}\n\n/** `time(tf, session, timezone)` / `time_close(...)` periods of the run's chart (see session/context `sessionPeriods`). */\nfunction chartSessionPeriods(timeframeString: string, session?: string, timezone?: string): SessionPeriods {\n const { bars } = sessionBars();\n return sessionPeriods(bars, { ...chartCtx, timezone: exchangeTimezone() }, timeframeString, session, timezone);\n}\n\n/**\n * The open time of the period of `tf` that holds each bar, in UNIX milliseconds; na on bars outside `session`.\n * @param tf - Timeframe of the periods: \"D\", \"W\", \"60\"... Default: the chart's.\n * @param session - Session hours, e.g. \"0930-1600\"; bars outside it give na. Default: the symbol's.\n * @param timezone - Time zone of the session hours. Default: the exchange's.\n * @returns Series of period open times.\n */\nfunction timeFunction(tf?: string, session?: string, timezone?: string): Series {\n collector();\n const { open } = chartSessionPeriods(tf || chartTimeframe().period, session, timezone);\n return perBar((t) => open(t));\n}\n\n/**\n * The close time of the period of `tf` that holds each bar, in UNIX milliseconds; na on bars outside `session`.\n * @param tf - Timeframe of the periods: \"D\", \"W\", \"60\"... Default: the chart's.\n * @param session - Session hours, e.g. \"0930-1600\"; bars outside it give na. Default: the symbol's.\n * @param timezone - Time zone of the session hours. Default: the exchange's.\n * @returns Series of period close times.\n */\nfunction timeCloseFunction(tf?: string, session?: string, timezone?: string): Series {\n collector();\n const { close } = chartSessionPeriods(tf || chartTimeframe().period, session, timezone);\n return perBar((t) => close(t));\n}\n\n/** Current time of the run in ms, see `ChartContext.now`. */\nlet runNow = NaN;\n\n/** PineScript `timenow`: the current time in ms, the same on every bar of a run (`ChartContext.now`). */\nexport const timenow = new Series(ctxBars, () => {\n incremental.nonIncremental('timenow');\n return runNow;\n});\n\n/**\n * The open time of each bar, in UNIX milliseconds (a Series). Called as `time(tf?, session?, timezone?)`: the open\n * time of the `tf` period that holds the bar, na outside `session`.\n * @example\n * ```js\n * const newDay = time(\"D\").neq(time(\"D\").offset(1));\n * bgcolor(color.when(newDay, color.new(color.gray, 85)));\n * ```\n */\nexport const time = callableSeries(new Series(ctxBars, (b) => barTime(b)), timeFunction);\n\n/**\n * The close time of each bar, in UNIX milliseconds (a Series). Called as `time_close(tf?, session?, timezone?)`: the\n * close time of the `tf` period that holds the bar, na outside `session`.\n * @example\n * ```js\n * plot(time_close.sub(time).div(60000), \"Bar minutes\");\n * ```\n */\nexport const time_close = callableSeries(\n new Series(ctxBars, (_b, i) => sessionBars().bars.closeOf(barTime(ctxBars.bars[i]!), chartTimeframe().period)),\n timeCloseFunction\n);\n\n/** PineScript `time_tradingday`: 00:00 UTC of the trading day of each bar, in ms. */\nexport const time_tradingday = new Series(ctxBars, (b) => sessionBars().bars.tradingDayTime(barTime(b)));\n\nfunction changeOf(tf: string, firstBar = false): Series {\n const { bars } = sessionBars();\n // a bar without a period (after an early close) is no change, and neither is the bar after it\n const changed = (a: number, b: number): boolean => !Number.isNaN(a) && !Number.isNaN(b) && a !== b;\n return perBar((t, i, times) => ((i > 0 ? changed(bars.timeOf(t, tf), bars.timeOf(times[i - 1]!, tf)) : firstBar) ? 1 : 0));\n}\n\n/**\n * Default anchor of `ta.vwap` (#173, #178): the first bar and each bar whose trading day differs from the last bar\n * that has one. Bars after an early close have no day: the first of them continues the day before it, each further\n * one starts a new sum, and the next day starts on its first bar (where `timeframe.change(\"D\")` is false). On\n * D / W / M charts every bar.\n */\nfunction vwapAnchor(): Series {\n if (chartTimeframe().isdwm) return barFlag(() => true);\n const { bars } = sessionBars();\n let last = NaN;\n let previous = NaN;\n return perBar((t, i) => {\n const day = bars.timeOf(t, '1D');\n const isNew = i === 0 || (Number.isNaN(day) ? Number.isNaN(previous) : day !== last);\n if (!Number.isNaN(day)) last = day;\n previous = day;\n return isNew ? 1 : 0;\n });\n}\n\nfunction flag(key: keyof SessionFlags): Series {\n const { bars, regular } = sessionBars();\n const values = sessionFlags(ctxBars.bars.map(barTime), bars, regular)[key];\n return Series.fromArray(ctxBars, values.map((v) => (v ? 1 : 0)));\n}\n\n/** A 1 / 0 Series from a per-bar test on the bar index and the number of bars. */\nfunction barFlag(test: (i: number, n: number) => boolean): Series {\n const n = ctxBars.bars.length;\n return Series.fromArray(ctxBars, Array.from({ length: n }, (_, i) => (test(i, n) ? 1 : 0)));\n}\n\n/**\n * An intrabar run reads the flag on the same bars as the run before, with at most one bar more, and the flags only\n * differ on their last bars: the values are kept between runs (the series only reads them).\n */\nconst FLAG_TAIL = 3;\nconst flagValues = new Map<string, number[]>();\nfunction namedFlag(name: string, test: (i: number, n: number) => boolean): Series {\n if (!intrabarRun) return barFlag(test);\n const n = ctxBars.bars.length;\n let values = flagValues.get(name);\n if (!values || values.length > n) {\n values = Array.from({ length: n }, (_, i) => (test(i, n) ? 1 : 0));\n flagValues.set(name, values);\n } else {\n const from = Math.max(0, Math.min(values.length, n) - FLAG_TAIL);\n values.length = n;\n for (let i = from; i < n; i++) values[i] = test(i, n) ? 1 : 0;\n }\n return Series.fromArray(ctxBars, values);\n}\n\n/** Number of bars of the chart: an intrabar run ends before the chart's last bar. */\nconst chartBarCount = (n: number): number => (intrabarRun ? intrabarRun.lastBarIndex + 1 : n);\n\nconst lastRealtime = (i: number, n: number): boolean => i === n - 1 && chartCtx.realtime === true;\n\n/**\n * PineScript `barstate.*` (1 / 0 per bar). All bars but the last are confirmed history bars. The last bar is\n * confirmed only when the host says so (`ChartContext.lastBarConfirmed`, e.g. the closing update of a realtime\n * bar), and is a realtime bar only when it receives live updates (`ChartContext.realtime`); without live updates\n * it is a history bar, as in PineScript.\n * `islastconfirmedhistory` is the last bar when it is confirmed and not realtime, else the bar before it.\n */\nexport const barstate: BarstateNamespace = {\n get isfirst(): Series { return namedFlag('isfirst', (i) => i === 0); },\n get islast(): Series { return namedFlag('islast', (i, n) => i === chartBarCount(n) - 1); },\n get isconfirmed(): Series { return namedFlag('isconfirmed', (i, n) => i < n - 1 || chartCtx.lastBarConfirmed === true); },\n get isrealtime(): Series { return namedFlag('isrealtime', lastRealtime); },\n get ishistory(): Series { return namedFlag('ishistory', (i, n) => !lastRealtime(i, n)); },\n get isnew(): Series { return namedFlag('isnew', (i, n) => !lastRealtime(i, n) || chartCtx.lastBarNew !== false); },\n get islastconfirmedhistory(): Series {\n return namedFlag('islastconfirmedhistory', (i, n) => {\n // moves to the next bar with each new bar: not kept by an incremental run (#196), but the same in the intrabar\n // runs of a backtest (#206)\n if (!intrabarRun) incremental.nonIncremental('barstate.islastconfirmedhistory');\n const lastConfirmed = chartCtx.lastBarConfirmed === true && chartCtx.realtime !== true;\n const count = chartBarCount(n);\n return i === (lastConfirmed ? count - 1 : count - 2);\n });\n },\n};\n\n/**\n * PineScript `session.*` (1 / 0 per bar) and the constants `session.regular` / `session.extended`.\n * First and last bars are per session period; market / pre / post market use the regular hours.\n */\nexport const session: SessionNamespace = {\n regular: 'regular',\n extended: 'extended',\n get isfirstbar(): Series { return flag('isfirstbar'); },\n get islastbar(): Series { return flag('islastbar'); },\n get ismarket(): Series { return flag('ismarket'); },\n get ispremarket(): Series { return flag('ispremarket'); },\n get ispostmarket(): Series { return flag('ispostmarket'); },\n get isfirstbar_regular(): Series { return flag('isfirstbar_regular'); },\n get islastbar_regular(): Series { return flag('islastbar_regular'); },\n};\n\n// \u2500\u2500 request.security (issue #101) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** PineScript `barmerge.*` constants of `request.security`. */\nexport const barmerge: BarmergeNamespace = {\n gaps_on: 'gaps_on',\n gaps_off: 'gaps_off',\n lookahead_on: 'lookahead_on',\n lookahead_off: 'lookahead_off',\n} as const;\n\nconst HEIKIN_ASHI = 'heikinashi:';\n\n/** PineScript `ticker.heikinashi(symbol)` / `ticker.standard(symbol)` for the chart symbol. */\nexport const ticker: TickerNamespace = {\n heikinashi(symbol: string): string {\n return HEIKIN_ASHI + symbol;\n },\n standard(symbol: string): string {\n return symbol.startsWith(HEIKIN_ASHI) ? symbol.slice(HEIKIN_ASHI.length) : symbol;\n },\n};\n\n/** What an expression of `request.security` may return. */\nexport type SecurityValue = Series | number | boolean | Array<Series | number | boolean>;\n\nfunction valuesOf(value: Series | number | boolean, length: number): number[] {\n if (!(value instanceof Series)) return new Array<number>(length).fill(Number(value));\n if (value.bars !== ctxBars.bars) {\n throw new Error(\n 'request.security(): the expression returned a series computed on the chart bars. ' +\n 'Compute the series inside the expression, e.g. () => ta.ema(close, 10).'\n );\n }\n return value.toArray().slice();\n}\n\n/**\n * PineScript `request.security` on a timeframe equal to or higher than the chart's. For the chart symbol\n * (`syminfo.tickerid`, `\"\"`, `ticker.heikinashi(...)`, `ticker.standard(...)`) the higher-timeframe bars are built by\n * grouping the chart bars; another symbol's bars come from `ChartContext.bars` (#179) and are merged on the chart bars\n * by close time (lookahead off) or by open time / trading day (lookahead on), see `securityOther`. `expression` runs\n * on those bars (its `ta.*` calls, tuples, `timeframe.*` and `syminfo.*` see them). A lower timeframe throws.\n *\n * A symbol that does not exist (bars []) stops the script with \"Invalid symbol: X\", or gives na with\n * `ignore_invalid_symbol`.\n *\n * PineScript rules: lookahead off shows a period's value from the\n * bar that completes it; lookahead on from its first bar; gaps on keeps only the bar where the value appears.\n * Built bars can differ from the exchange's bars (official open / close, volume).\n */\nfunction security<T extends SecurityValue>(\n symbol: string,\n timeframe: string,\n expression: () => T,\n gaps: string = barmerge.gaps_off,\n lookahead: string = barmerge.lookahead_off,\n ignore_invalid_symbol: boolean = false\n): T extends unknown[] ? Series[] : Series {\n collector();\n // other bars merged on the chart bars: not resumed by an incremental run (#196)\n incremental.nonIncremental('request.security');\n const heikin = symbol.startsWith(HEIKIN_ASHI);\n const base = heikin ? symbol.slice(HEIKIN_ASHI.length) : symbol;\n const chart = chartTimeframe();\n const tf = timeframeCore.info(timeframe || chart.period).period;\n if (base !== '' && base !== chartCtx.tickerid) {\n return externalSecurity(base, heikin, tf, expression, gaps, lookahead, ignore_invalid_symbol, false);\n }\n const ticks = timeframeCore.info(tf).isticks && tf !== chart.period;\n if (ticks || timeframeCore.in_seconds(tf) < timeframeCore.in_seconds(chart.period)) {\n // a lower timeframe of the chart symbol, or its ticks: its bars come from ChartContext.bars (#181, #214)\n return externalSecurity(chartCtx.tickerid ?? '', heikin, tf, expression, gaps, lookahead, ignore_invalid_symbol, true);\n }\n\n const chartBars = ctxBars.bars;\n const times = chartBars.map(barTime);\n let htf: Bar[];\n let group: number[];\n let latest: number[];\n if (tf === chart.period) {\n htf = chartBars;\n group = chartBars.map((_, i) => i);\n latest = group;\n } else {\n const { bars: loaded, regular } = sessionBars();\n // D / W / M periods follow the regular hours; intraday periods the loaded session\n const calendar = timeframeCore.info(tf).isdwm ? regular : loaded;\n const starts = times.map((t) => calendar.timeOf(t, tf));\n const dayPeriods = times.map((t, i) => {\n const at = loaded.locateBar(t);\n const periods = at ? calendar.calendar.periods(at.date) : [];\n return periods.length ? calendar.timeOf(periods[0]![0], tf) : starts[i]!;\n });\n const tfInfo = timeframeCore.info(tf);\n strayPeriods(starts, dayPeriods, times, loaded, tfInfo.isdwm ? null : timeframeCore.in_seconds(tf) * 1000);\n const reaches = times.map((t) => loaded.closeOf(t, chart.period) >= calendar.periodEnd(t, tf));\n ({ group, latest } = periodsOf(starts, dayPeriods, reaches));\n const unit = chartCtx.timeUnit === 'ms' ? 1 : 1000;\n // a higher-timeframe bar ends at the bar that completes it (no value from after the completion)\n const after = afterCompletion(group, latest);\n const kept = (_: unknown, i: number): boolean => !after[i];\n htf = resample(chartBars.filter(kept), starts.map((s) => s / unit).filter(kept)).bars;\n }\n if (heikin) htf = heikinAshi(htf);\n\n const savedCtx = chartCtx;\n let result: T;\n let values: number[][];\n ctxBars.setAll(htf);\n chartCtx = { ...chartCtx, timeframe: tf, mainTimeframe: chartCtx.mainTimeframe ?? chartCtx.timeframe };\n try {\n result = expression();\n const parts = Array.isArray(result) ? result : [result];\n values = parts.map((p) => valuesOf(p, htf.length));\n } finally {\n ctxBars.setAll(chartBars);\n chartCtx = savedCtx;\n }\n const mapped = values.map((v) =>\n Series.fromArray(ctxBars, mapToChart(v, group, latest, lookahead === barmerge.lookahead_on, gaps === barmerge.gaps_on))\n );\n return (Array.isArray(result) ? mapped : mapped[0]) as T extends unknown[] ? Series[] : Series;\n}\n\n/** Bars of a symbol on a timeframe from `ChartContext.bars`, with its calendar and the values of `expression` on them. */\ninterface ExternalRun<T> {\n bars: Bar[];\n info: SymbolInfo;\n result: T;\n values: number[][];\n}\n\n/**\n * Runs `expression` on the bars of `symbol` / `tf` given by `ChartContext.bars` (#179, #181). Bars not given: the\n * request is recorded for the {@link MissingSymbolDataError} and the expression runs on no bar. `own`: the chart\n * symbol, whose calendar defaults to the chart's.\n */\nfunction runExternal<T extends SecurityValue>(\n symbol: string,\n heikin: boolean,\n tf: string,\n expression: () => T,\n ignoreInvalid: boolean,\n own: boolean\n): ExternalRun<T> {\n let bars = chartCtx.bars?.(symbol, tf);\n if (bars === undefined && !missingSymbols.some((r) => r.symbol === symbol && r.timeframe === tf)) {\n missingSymbols.push({ symbol, timeframe: tf });\n }\n if (bars !== undefined && bars.length === 0 && !ignoreInvalid) throw new Error(`Invalid symbol: ${symbol}`);\n bars ??= [];\n if (heikin) bars = heikinAshi(bars);\n const given = chartCtx.symbolInfo?.(symbol);\n const info: SymbolInfo = own ? { ...chartCtx, ...given } : (given ?? {});\n const chartBars = ctxBars.bars;\n const savedCtx = chartCtx;\n let result: T;\n let values: number[][];\n ctxBars.setAll(bars);\n // the expression sees that symbol: its ticker, timeframe, calendar and properties (the chart's own symbol stays the\n // main one)\n const seen: ChartContext = {\n ...chartCtx,\n tickerid: symbol,\n timeframe: tf,\n mainTickerid: chartCtx.mainTickerid ?? chartCtx.tickerid,\n mainTimeframe: chartCtx.mainTimeframe ?? chartCtx.timeframe,\n };\n for (const key of SYMBOL_INFO_KEYS) (seen as Record<string, unknown>)[key] = info[key];\n chartCtx = seen;\n try {\n result = expression();\n const parts = Array.isArray(result) ? result : [result];\n values = parts.map((p) => valuesOf(p, bars!.length));\n } finally {\n ctxBars.setAll(chartBars);\n chartCtx = savedCtx;\n }\n return { bars, info, result, values };\n}\n\n/** The chart for the merge functions of `security/other`. */\nfunction mergeChart(): OtherSymbolChart {\n return {\n timeframe: chartTimeframe().period,\n timezone: chartCtx.timezone,\n session: chartCtx.session,\n timeUnit: chartCtx.timeUnit,\n // the realtime rule applies to a last bar that receives live updates\n lastBarConfirmed: chartCtx.realtime !== true,\n };\n}\n\n/**\n * `request.security` of another symbol (#179), or of the chart symbol on a lower timeframe (#181): its bars from\n * `ChartContext.bars`, merged by `securityOther`.\n */\nfunction externalSecurity<T extends SecurityValue>(\n symbol: string,\n heikin: boolean,\n tf: string,\n expression: () => T,\n gaps: string,\n lookahead: string,\n ignoreInvalid: boolean,\n own: boolean\n): T extends unknown[] ? Series[] : Series {\n const { bars, info, result, values } = runExternal(symbol, heikin, tf, expression, ignoreInvalid, own);\n const index = securityOther(ctxBars.bars, bars, tf, mergeChart(), {\n gaps: gaps === barmerge.gaps_on,\n lookahead: lookahead === barmerge.lookahead_on,\n other: info,\n });\n const mapped = values.map((v) => Series.fromArray(ctxBars, index.map((j) => (j < 0 ? NaN : (v[j] ?? NaN)))));\n return (Array.isArray(result) ? mapped : mapped[0]) as T extends unknown[] ? Series[] : Series;\n}\n\n/**\n * PineScript `request.security_lower_tf(symbol, timeframe, expression, ignore_invalid_symbol)` (#181): for each\n * chart bar, the array of the values of `expression` on the bars of the lower timeframe that the chart bar contains\n * (those whose close is after the open of the chart bar and at or before its close; empty when there are none).\n * The bars come from `ChartContext.bars`, for the chart symbol (`\"\"`, `syminfo.tickerid`) as for another symbol.\n * Returns one array per chart bar (oldest first), or one such list per tuple part.\n * @throws Error when `timeframe` is higher than the chart timeframe\n */\nfunction security_lower_tf<T extends SecurityValue>(\n symbol: string,\n timeframe: string,\n expression: () => T,\n ignore_invalid_symbol: boolean = false\n): T extends unknown[] ? number[][][] : number[][] {\n collector();\n incremental.nonIncremental('request.security_lower_tf');\n const heikin = symbol.startsWith(HEIKIN_ASHI);\n const base = heikin ? symbol.slice(HEIKIN_ASHI.length) : symbol;\n const chart = chartTimeframe();\n const tf = timeframeCore.info(timeframe || chart.period).period;\n if (timeframeCore.in_seconds(tf) > timeframeCore.in_seconds(chart.period)) {\n throw new Error(`request.security_lower_tf: timeframe \"${tf}\" is higher than the chart timeframe \"${chart.period}\".`);\n }\n const own = base === '' || base === chartCtx.tickerid;\n const ticker = own ? (chartCtx.tickerid ?? '') : base;\n const { bars, info, result, values } = runExternal(ticker, heikin, tf, expression, ignore_invalid_symbol, own);\n const ranges = securityLowerTf(ctxBars.bars, bars, tf, mergeChart(), { other: info });\n const mapped = values.map((v) => ranges.map(([from, to]) => v.slice(from, to)));\n return (Array.isArray(result) ? mapped : mapped[0]) as T extends unknown[] ? number[][][] : number[][];\n}\n\n/**\n * PineScript `request.seed(source, symbol, expression, ignore_invalid_symbol)` (#205): `expression` on a seed data\n * series, on the chart timeframe. The series is the symbol `ChartContext.seedSymbol(source, symbol)` (default\n * `\"<SOURCE>:<SYMBOL>\"` upper-cased), read as `request.security(<that symbol>, \"\", expression)`.\n */\nfunction seed<T extends SecurityValue>(\n source: string,\n symbol: string,\n expression: () => T,\n ignore_invalid_symbol: boolean = false\n): T extends unknown[] ? Series[] : Series {\n const ticker = chartCtx.seedSymbol?.(source, symbol) ?? `${source.toUpperCase()}:${symbol.toUpperCase()}`;\n return security(ticker, '', expression, barmerge.gaps_off, barmerge.lookahead_off, ignore_invalid_symbol);\n}\n\n/** PineScript `request.*`: `security` (issue #101, other symbols #179, lower timeframes #181), `security_lower_tf` and `seed` (#205). */\n/** PineScript parameters of `request.security` / `request.security_lower_tf`, in their positional order. */\nconst SECURITY_PARAMETERS = ['symbol', 'timeframe', 'expression', 'gaps', 'lookahead', 'ignore_invalid_symbol', 'currency', 'calc_bars_count'] as const;\nconst SECURITY_LOWER_TF_PARAMETERS = ['symbol', 'timeframe', 'expression', 'ignore_invalid_symbol', 'currency', 'ignore_invalid_timeframe', 'calc_bars_count'] as const;\nconst SEED_PARAMETERS = ['source', 'symbol', 'expression', 'ignore_invalid_symbol', 'calc_bars_count'] as const;\n\n/** Named arguments of `request.security` (PineScript names). */\nexport interface SecurityArgs<T extends SecurityValue = SecurityValue> {\n symbol?: string;\n timeframe?: string;\n expression?: () => T;\n gaps?: string;\n lookahead?: string;\n ignore_invalid_symbol?: boolean;\n currency?: string;\n calc_bars_count?: number;\n}\n\n/** Named arguments of `request.security_lower_tf` (PineScript names). */\nexport interface SecurityLowerTfArgs<T extends SecurityValue = SecurityValue> {\n symbol?: string;\n timeframe?: string;\n expression?: () => T;\n ignore_invalid_symbol?: boolean;\n currency?: string;\n ignore_invalid_timeframe?: boolean;\n calc_bars_count?: number;\n}\n\n/** `currency` and `calc_bars_count` change the values in PineScript: they throw instead of being ignored. */\nfunction unsupportedSecurityArgs(name: string, currency: unknown, calcBarsCount: unknown): void {\n if (currency !== undefined && currency !== '' && currency !== 'NONE') {\n throw new Error(`${name}(): the currency argument (conversion of the values) is not supported.`);\n }\n if (calcBarsCount !== undefined) throw new Error(`${name}(): the calc_bars_count argument is not supported.`);\n}\n\n/** `request.security` with PineScript's named arguments: `request.security(sym, \"D\", () => close, { lookahead: barmerge.lookahead_on })`. */\nfunction securityCall<T extends SecurityValue>(\n ...args:\n | [symbol: string, timeframe: string, expression: () => T, gaps?: string, lookahead?: string, ignore_invalid_symbol?: boolean]\n | [symbol: string, timeframe: string, expression: () => T, args: SecurityArgs<T>]\n | [args: SecurityArgs<T> & { symbol: string; timeframe: string; expression: () => T }]\n): T extends unknown[] ? Series[] : Series {\n const a = namedArguments('request.security', SECURITY_PARAMETERS, args);\n unsupportedSecurityArgs('request.security', a[6], a[7]);\n return security(a[0] as string, a[1] as string, a[2] as () => T, a[3] as string | undefined, a[4] as string | undefined, a[5] as boolean | undefined);\n}\n\n/** `request.security_lower_tf` with PineScript's named arguments. */\nfunction securityLowerTfCall<T extends SecurityValue>(\n ...args:\n | [symbol: string, timeframe: string, expression: () => T, ignore_invalid_symbol?: boolean]\n | [symbol: string, timeframe: string, expression: () => T, args: SecurityLowerTfArgs<T>]\n | [args: SecurityLowerTfArgs<T> & { symbol: string; timeframe: string; expression: () => T }]\n): T extends unknown[] ? number[][][] : number[][] {\n const a = namedArguments('request.security_lower_tf', SECURITY_LOWER_TF_PARAMETERS, args);\n unsupportedSecurityArgs('request.security_lower_tf', a[4], a[6]);\n if (a[5] !== undefined && a[5] !== false) throw new Error('request.security_lower_tf(): the ignore_invalid_timeframe argument is not supported.');\n return security_lower_tf(a[0] as string, a[1] as string, a[2] as () => T, a[3] as boolean | undefined);\n}\n\n/** Named arguments of `request.seed` (PineScript names). */\nexport interface SeedArgs<T extends SecurityValue = SecurityValue> {\n source?: string;\n symbol?: string;\n expression?: () => T;\n ignore_invalid_symbol?: boolean;\n calc_bars_count?: number;\n}\n\n/** `request.seed` with PineScript's named arguments. */\nfunction seedCall<T extends SecurityValue>(\n ...args:\n | [source: string, symbol: string, expression: () => T, ignore_invalid_symbol?: boolean]\n | [source: string, symbol: string, expression: () => T, args: SeedArgs<T>]\n | [args: SeedArgs<T> & { source: string; symbol: string; expression: () => T }]\n): T extends unknown[] ? Series[] : Series {\n const a = namedArguments('request.seed', SEED_PARAMETERS, args);\n unsupportedSecurityArgs('request.seed', undefined, a[4]);\n return seed(a[0] as string, a[1] as string, a[2] as () => T, a[3] as boolean | undefined);\n}\n\n// \u2500\u2500 request.dividends / request.splits / request.earnings (#211) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The events of `ticker` (\"\" or the chart's: the chart symbol); {} while the host has not given them (the run ends with\n * a MissingSymbolDataError). */\nfunction symbolEvents(ticker: string): SymbolEvents {\n collector();\n const symbol = ticker === '' ? chartTickerid() : ticker;\n const events = chartCtx.events?.(symbol);\n if (events === undefined) {\n if (!missingSymbols.some((r) => r.events && r.symbol === symbol)) missingSymbols.push({ symbol, timeframe: '', events: true });\n return {};\n }\n return events;\n}\n\n/** One value of each event; throws when no event has it (the host does not have it), na where one has none. */\nfunction eventField<E extends object>(list: E[], field: keyof E, name: string, ticker: string): number[] {\n if (list.length && list.every((e) => e[field] === undefined)) {\n throw new Error(`${name}: the ${String(field)} values of ${ticker || 'the chart symbol'} are not known.`);\n }\n return list.map((e) => {\n const v = e[field] as unknown;\n return typeof v === 'number' ? v : NaN;\n });\n}\n\n/** A Series of event values on the chart bars, placed by PineScript's rules (see `security/events`). */\nfunction eventSeries(times: number[], values: number[], gaps: string | undefined, lookahead: string | undefined): Series {\n incremental.nonIncremental('request.dividends / splits / earnings');\n const opens = ctxBars.bars.map(barTime);\n const tf = chartTimeframe().period;\n const span = timeframeCore.info(tf).isticks ? 0 : timeframeCore.in_seconds(tf) * 1000;\n const { bars } = sessionBars();\n // a bar without a session period closes where the next one opens\n const closes = opens.map((t, i) => {\n const c = bars.closeOf(t, tf);\n return Number.isFinite(c) ? c : (opens[i + 1] ?? t + span);\n });\n const order = times.map((_, i) => i).sort((a, b) => times[a]! - times[b]!);\n const events = order.map((i) => ({ time: times[i]!, value: values[i]! }));\n return Series.fromArray(\n ctxBars,\n eventsOnBars(opens, closes, tf, events, { gaps: gaps === barmerge.gaps_on, lookahead: lookahead === barmerge.lookahead_on })\n );\n}\n\n/** PineScript `dividends.*`: the fields of `request.dividends` and the next announced dividend of the chart symbol. */\nexport const dividends: DividendsNamespace = {\n net: 'net',\n gross: 'gross',\n /** Amount of the next dividend (net), na when none is announced */\n get future_amount(): number {\n return nextDividend()?.net ?? NaN;\n },\n /** Ex-date of the next dividend (ms) */\n get future_ex_date(): number {\n return nextDividend()?.time ?? NaN;\n },\n /** Payment date of the next dividend (ms) */\n get future_pay_date(): number {\n return nextDividend()?.payDate ?? NaN;\n },\n} as const;\n\n/** PineScript `splits.*`: the fields of `request.splits`. */\nexport const splits: SplitsNamespace = { numerator: 'numerator', denominator: 'denominator' } as const;\n\n/** PineScript `earnings.*`: the fields of `request.earnings` and the next earnings release of the chart symbol. */\nexport const earnings: EarningsNamespace = {\n actual: 'actual',\n estimate: 'estimate',\n standardized: 'standardized',\n /** Estimated earnings per share of the next release */\n get future_eps(): number {\n return nextEarnings()?.estimate ?? NaN;\n },\n /** Estimated revenue of the next release */\n get future_revenue(): number {\n return nextEarnings()?.revenueEstimate ?? NaN;\n },\n /** Time of the next release (ms) */\n get future_time(): number {\n return nextEarnings()?.time ?? NaN;\n },\n /** End of the fiscal period of the next release (ms) */\n get future_period_end_time(): number {\n return nextEarnings()?.periodEnd ?? NaN;\n },\n} as const;\n\n/** The first event after the current time of the run in the chart symbol's list, when the host gives the announced ones. */\nfunction nextEvent<K extends 'dividends' | 'earnings'>(kind: K): NonNullable<SymbolEvents[K]>[number] | undefined {\n const events = symbolEvents('');\n if (!Object.keys(events).length) return undefined;\n if (!events.future?.[kind]) throw new Error(`${kind}.future_*: the announced ${kind} of ${chartTickerid()} are not known.`);\n return (events[kind] as Array<{ time: number }> | undefined)?.find((e) => e.time > runNow) as NonNullable<SymbolEvents[K]>[number] | undefined;\n}\nconst nextDividend = (): DividendEvent | undefined => nextEvent('dividends');\nconst nextEarnings = (): EarningsEvent | undefined => nextEvent('earnings');\n\nconst DIVIDENDS_PARAMETERS = ['ticker', 'field', 'gaps', 'lookahead', 'ignore_invalid_symbol', 'currency'] as const;\nconst SPLITS_PARAMETERS = ['ticker', 'field', 'gaps', 'lookahead', 'ignore_invalid_symbol'] as const;\n\n/** Named arguments of `request.dividends` / `request.earnings` (`request.splits` has no `currency`). */\nexport interface EventRequestArgs {\n ticker?: string;\n field?: string;\n gaps?: string;\n lookahead?: string;\n ignore_invalid_symbol?: boolean;\n currency?: string;\n}\n\ntype EventRequestCall =\n | [ticker: string, field?: string, gaps?: string, lookahead?: string, ignore_invalid_symbol?: boolean, currency?: string]\n | [ticker: string, field: string, args: EventRequestArgs]\n | [ticker: string, args: EventRequestArgs]\n | [args: EventRequestArgs & { ticker: string }];\n\n/**\n * PineScript `request.dividends(ticker, field, gaps, lookahead, ignore_invalid_symbol, currency)`: the dividend per\n * share (`dividends.net`, default, or `dividends.gross`) as declared, from the bar after its ex-date's day (see\n * `security/events`). na before the first dividend. The events come from `ChartContext.events`.\n */\nfunction dividendsCall(...args: EventRequestCall): Series {\n const a = namedArguments('request.dividends', DIVIDENDS_PARAMETERS, args);\n unsupportedSecurityArgs('request.dividends', a[5], undefined);\n const ticker = (a[0] as string | undefined) ?? '';\n const field = (a[1] as string | undefined) ?? dividends.net;\n if (field !== dividends.net && field !== dividends.gross) throw new Error(`request.dividends(): unknown field \"${field}\": dividends.net or dividends.gross.`);\n const list = symbolEvents(ticker).dividends ?? [];\n const values = field === dividends.gross ? list.map((d) => d.gross ?? d.net) : eventField(list, 'net', 'request.dividends', ticker);\n return eventSeries(list.map((d) => d.time), values, a[2] as string | undefined, a[3] as string | undefined);\n}\n\n/**\n * PineScript `request.splits(ticker, field, gaps, lookahead, ignore_invalid_symbol)`: the numerator\n * (`splits.numerator`) or the denominator (`splits.denominator`) of the last split, from the bar after its day.\n */\nfunction splitsCall(...args: EventRequestCall): Series {\n const a = namedArguments('request.splits', SPLITS_PARAMETERS, args);\n const ticker = (a[0] as string | undefined) ?? '';\n const field = a[1] as string | undefined;\n if (field !== splits.numerator && field !== splits.denominator) {\n throw new Error('request.splits(): the field is splits.numerator or splits.denominator.');\n }\n const list = symbolEvents(ticker).splits ?? [];\n return eventSeries(list.map((s) => s.time), eventField(list, field, 'request.splits', ticker), a[2] as string | undefined, a[3] as string | undefined);\n}\n\n/**\n * PineScript `request.earnings(ticker, field, gaps, lookahead, ignore_invalid_symbol, currency)`: earnings per share of\n * the last release (`earnings.actual`, default, `earnings.estimate` or `earnings.standardized`), from the bar after the\n * period of the chart timeframe it was published in (the next day on a daily chart).\n */\nfunction earningsCall(...args: EventRequestCall): Series {\n const a = namedArguments('request.earnings', DIVIDENDS_PARAMETERS, args);\n unsupportedSecurityArgs('request.earnings', a[5], undefined);\n const ticker = (a[0] as string | undefined) ?? '';\n const field = (a[1] as string | undefined) ?? earnings.actual;\n if (field !== earnings.actual && field !== earnings.estimate && field !== earnings.standardized) {\n throw new Error(`request.earnings(): unknown field \"${field}\": earnings.actual, earnings.estimate or earnings.standardized.`);\n }\n // announced releases still to come have no values yet\n const list = (symbolEvents(ticker).earnings ?? []).filter((e) => e.time <= runNow);\n return eventSeries(list.map((e) => e.time), eventField(list, field, 'request.earnings', ticker), a[2] as string | undefined, a[3] as string | undefined);\n}\n\nconst requestMembers = strictNamespace('request', {\n security: securityCall,\n security_lower_tf: securityLowerTfCall,\n seed: seedCall,\n dividends: dividendsCall,\n splits: splitsCall,\n earnings: earningsCall,\n});\n/**\n * Data from other symbols, timeframes and sources: `request.security` (another symbol or timeframe),\n * `request.security_lower_tf` (the lower-timeframe bars inside each bar), `request.seed` (a separately published data series),\n * dividends, splits and earnings. Call it before any `eachBar()` loop.\n * @example\n * ```js\n * const dailyClose = request.security(\"\", \"D\", () => close);\n * plot(dailyClose, \"Daily close\");\n * ```\n */\nexport const request: RequestNamespace = requestMembers;\nsameKeys<typeof requestMembers, RequestNamespace>(true);\n\n// \u2500\u2500 Drawing objects \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// The drawing namespaces come from this bundle so that they share the registry that\n// executeScript() resets. `line.all` etc. are read like PineScript variables.\n\n/** PineScript `line.*`; `line.all` lists the live lines in creation order. */\n// \u2500\u2500 Drawing namespaces (named arguments, Series arguments in bar loops) \u2500\u2500\u2500\u2500\u2500\u2500\n\ntype Numeric = number | Series;\n/** A function whose number parameters also take a Series (read on the current bar inside a bar loop). */\ntype WithSeries<F> = F extends (...args: infer A) => infer R\n ? (...args: { [K in keyof A]: number extends A[K] ? A[K] | Series : A[K] }) => R\n : never;\ntype ScriptDrawing<T> = { [K in keyof T]: T[K] extends (...args: never[]) => unknown ? T[K] & WithSeries<T[K]> : T[K] };\ntype Colour = string | undefined;\n\n/** Named arguments of `label.new` (PineScript parameter names). */\nexport interface LabelNewArgs {\n x?: Numeric;\n y?: Numeric;\n point?: ChartPoint;\n text?: string;\n xloc?: 'bar_index' | 'bar_time' | 'pane';\n yloc?: 'price' | 'abovebar' | 'belowbar';\n color?: Colour;\n style?: NonNullable<Label['style']>;\n textcolor?: Colour;\n size?: string | number;\n textalign?: 'left' | 'center' | 'right';\n tooltip?: string;\n text_font_family?: 'default' | 'monospace';\n force_overlay?: boolean;\n text_formatting?: number;\n}\n\n/** Named arguments of `line.new`. */\nexport interface LineNewArgs {\n x1?: Numeric;\n y1?: Numeric;\n x2?: Numeric;\n y2?: Numeric;\n first_point?: ChartPoint;\n second_point?: ChartPoint;\n xloc?: 'bar_index' | 'bar_time' | 'pane';\n extend?: 'none' | 'left' | 'right' | 'both';\n color?: Colour;\n style?: 'solid' | 'dotted' | 'dashed' | 'arrow_left' | 'arrow_right' | 'arrow_both';\n width?: Numeric;\n force_overlay?: boolean;\n}\n\n/** Named arguments of `box.new`. */\nexport interface BoxNewArgs {\n left?: Numeric;\n top?: Numeric;\n right?: Numeric;\n bottom?: Numeric;\n top_left?: ChartPoint;\n bottom_right?: ChartPoint;\n border_color?: Colour;\n border_width?: Numeric;\n border_style?: 'solid' | 'dotted' | 'dashed';\n extend?: 'none' | 'left' | 'right' | 'both';\n xloc?: 'bar_index' | 'bar_time' | 'pane';\n bgcolor?: Colour;\n text?: string;\n text_size?: string | number;\n text_color?: Colour;\n text_halign?: 'left' | 'center' | 'right';\n text_valign?: 'top' | 'center' | 'bottom';\n text_wrap?: 'none' | 'auto';\n text_font_family?: 'default' | 'monospace';\n force_overlay?: boolean;\n text_formatting?: number;\n}\n\n/** Named arguments of `table.new`. */\nexport interface TableNewArgs {\n position?: string;\n columns?: number;\n rows?: number;\n bgcolor?: Colour;\n frame_color?: Colour;\n frame_width?: number;\n border_color?: Colour;\n border_width?: number;\n force_overlay?: boolean;\n}\n\n/** Named arguments of `table.cell`. */\nexport interface TableCellArgs {\n table_id?: Table;\n column?: number;\n row?: number;\n text?: string;\n width?: number;\n height?: number;\n text_color?: Colour;\n text_halign?: 'left' | 'center' | 'right';\n text_valign?: 'top' | 'center' | 'bottom';\n text_size?: string | number;\n bgcolor?: Colour;\n tooltip?: string;\n text_font_family?: 'default' | 'monospace';\n text_formatting?: number;\n}\n\n/** Named arguments of `polyline.new`. */\nexport interface PolylineNewArgs {\n points?: ChartPoint[];\n curved?: boolean;\n closed?: boolean;\n xloc?: 'bar_index' | 'bar_time' | 'pane';\n line_color?: Colour;\n fill_color?: Colour | null;\n line_style?: 'solid' | 'dotted' | 'dashed';\n line_width?: number;\n force_overlay?: boolean;\n}\n\n/** Named arguments of `linefill.new`. */\nexport interface LinefillNewArgs {\n line1?: Line;\n line2?: Line;\n color?: Colour;\n}\n\nconst loopBar = (): number => currentBar;\n\n/** Wraps a drawing namespace and keeps its `all` getter (the live drawings in creation order). */\n/** A drawing namespace of scripts: the members of `T`, and `all`. */\ntype DrawingNamespace<T, D> = Omit<ScriptDrawing<T>, 'all'> & {\n /** The live drawings of this kind, oldest first (a new array on each read). */\n readonly all: D[];\n};\n\nfunction drawings<T extends Record<string, unknown>, D>(name: string, members: T, all: () => D[]): DrawingNamespace<T, D> {\n const out = drawingNamespace(name, members, loopBar) as ScriptDrawing<T>;\n return Object.defineProperty(out, 'all', { get: all, enumerable: true }) as DrawingNamespace<T, D>;\n}\n\n// The members are typed by their modules, so that the editor shows each function's documentation.\nconst lineNs: DrawingNamespace<typeof lineCore & typeof pineConstants.lineStyles, Line> = drawings(\n 'line',\n { ...lineCore, ...pineConstants.lineStyles },\n () => lineCore.all()\n);\n/**\n * Lines between two chart points: `line.new()` draws one, `line.set_*` / `line.get_*` move and read it, `line.style_*`\n * are its styles, `line.all` lists the live lines.\n */\nexport const line = lineNs as typeof lineNs & {\n new: ((args: LineNewArgs) => Line) &\n ((x1: Numeric, y1: Numeric, x2: Numeric, y2: Numeric, args: LineNewArgs) => Line) &\n ((first_point: ChartPoint, second_point: ChartPoint, args: LineNewArgs) => Line);\n};\n\nconst labelNs: DrawingNamespace<typeof labelCore & typeof pineConstants.labelStyles, Label> = drawings(\n 'label',\n { ...labelCore, ...pineConstants.labelStyles },\n () => labelCore.all()\n);\n/**\n * Text boxes and shapes at a chart point: `label.new()` draws one, `label.set_*` / `label.get_*` change and read it,\n * `label.style_*` are its styles, `label.all` lists the live labels.\n */\nexport const label = labelNs as typeof labelNs & {\n new: ((args: LabelNewArgs) => Label) &\n ((x: Numeric, y: Numeric, args: LabelNewArgs) => Label) &\n ((x: Numeric, y: Numeric, text: string, args: LabelNewArgs) => Label) &\n ((point: ChartPoint, args: LabelNewArgs) => Label) &\n ((point: ChartPoint, text: string, args: LabelNewArgs) => Label);\n};\n\nconst boxNs: DrawingNamespace<typeof boxCore, Box> = drawings('box', { ...boxCore }, () => boxCore.all());\n/**\n * Rectangles between two x coordinates and two prices, with optional text: `box.new()` draws one, `box.set_*` /\n * `box.get_*` change and read it, `box.all` lists the live boxes.\n */\nexport const box = boxNs as typeof boxNs & {\n new: ((args: BoxNewArgs) => Box) &\n ((left: Numeric, top: Numeric, right: Numeric, bottom: Numeric, args: BoxNewArgs) => Box) &\n ((top_left: ChartPoint, bottom_right: ChartPoint, args: BoxNewArgs) => Box);\n};\n\nconst linefillNs: DrawingNamespace<typeof linefillCore, Linefill> = drawings('linefill', { ...linefillCore }, () => linefillCore.all());\n/**\n * Colour fills between two lines that follow the lines when they move: `linefill.new()`, `linefill.set_color()`,\n * `linefill.all`.\n */\nexport const linefill = linefillNs as typeof linefillNs & {\n new: ((args: LinefillNewArgs) => Linefill) & ((line1: Line, line2: Line, args: LinefillNewArgs) => Linefill);\n};\n\nconst polylineNs: DrawingNamespace<typeof polylineCore, Polyline> = drawings('polyline', { ...polylineCore }, () => polylineCore.all());\n/**\n * Shapes through many chart points, straight or curved, open or closed and filled: `polyline.new()`,\n * `polyline.delete()`, `polyline.all`.\n */\nexport const polyline = polylineNs as typeof polylineNs & {\n new: ((args: PolylineNewArgs) => Polyline) & ((points: ChartPoint[], args: PolylineNewArgs) => Polyline);\n};\n\nconst tableNs: DrawingNamespace<typeof tableCore, Table> = drawings('table', { ...tableCore }, () => tableCore.all());\n/**\n * Tables fixed at a place of the pane, for values and dashboards: `table.new()` creates one, `table.cell()` fills it,\n * `table.all` lists the live tables. The live tables go to `result.tables`.\n */\nexport const table: TableNamespace = tableNs as typeof tableNs & {\n new: ((args: TableNewArgs) => Table) & ((position: string, columns: number, rows: number, args: TableNewArgs) => Table);\n cell: ((args: TableCellArgs) => void) &\n ((table_id: Table, column: number, row: number, args: TableCellArgs) => void) &\n ((table_id: Table, column: number, row: number, text: string, args: TableCellArgs) => void);\n};\nsameKeys<typeof tableNs, TableNamespace>(true);\n\n/** PineScript `position.*` constants (table positions). */\nexport { position };\n\n/** Text constants: `text.format_*` (bold, italic), `text.align_*` (alignment) and `text.wrap_*` (wrapping). */\nexport const text: typeof textCore = { ...textCore };\n\n// The constant namespaces (`shape.triangleup`, `size.small`, `xloc.bar_time`...), each documented in constants.ts.\nexport { shape, location, size, xloc, yloc, extend, display, format, font, scale, order, currency, adjustment } from './constants.js';\n\n/**\n * PineScript `chart.point.*`. `chart.point.now(price?)` is the point of the current bar\n * (index, time, and `price`, default the close), so it runs inside eachBar().\n */\nexport const chart: ChartNamespace = {\n /** Chart foreground colour (PineScript `chart.fg_color`), from the chart context. */\n get fg_color(): string {\n return chartText('foregroundColor', 'chart.fg_color');\n },\n /** Chart background colour (PineScript `chart.bg_color`), from the chart context. */\n get bg_color(): string {\n return chartText('backgroundColor', 'chart.bg_color');\n },\n /** Time (ms) of the first bar in view (PineScript `chart.left_visible_bar_time`), from the chart context; without it,\n * of the first bar. */\n get left_visible_bar_time(): number {\n return visibleBarTime(chartCtx.leftVisibleBarTime, 0);\n },\n /** Time (ms) of the last bar in view (PineScript `chart.right_visible_bar_time`), from the chart context; without it,\n * of the last bar. */\n get right_visible_bar_time(): number {\n return visibleBarTime(chartCtx.rightVisibleBarTime, ctxBars.bars.length - 1);\n },\n /** The chart is not one of the types below (PineScript `chart.is_standard`). */\n get is_standard(): boolean {\n return chartTypeIs('standard');\n },\n get is_heikinashi(): boolean {\n return chartTypeIs('heikinashi');\n },\n get is_renko(): boolean {\n return chartTypeIs('renko');\n },\n get is_kagi(): boolean {\n return chartTypeIs('kagi');\n },\n get is_linebreak(): boolean {\n return chartTypeIs('linebreak');\n },\n get is_pnf(): boolean {\n return chartTypeIs('pnf');\n },\n get is_range(): boolean {\n return chartTypeIs('range');\n },\n point: {\n ...chartPointCore,\n now(price?: number): ChartPoint {\n collector();\n if (currentBar < 0) {\n throw new Error('chart.point.now() needs a current bar: call it inside eachBar().');\n }\n const bar = ctxBars.bars[currentBar]!;\n return chartPointCore.new_point(barTime(bar), currentBar, price ?? bar.close);\n },\n },\n};\n\n/**\n * Makes a Series from an array of numbers, one per bar (oldest first), e.g. values collected inside `eachBar()`.\n * @param values - One value per bar; NaN is na.\n * @returns Series of the values.\n * @example\n * ```js\n * const ranges = [];\n * eachBar((c) => { ranges.push(c.high - c.low); });\n * plot(seriesOf(ranges), \"Range\");\n * ```\n */\nexport function seriesOf(values: number[]): Series {\n collector();\n return Series.fromArray(ctxBars, values);\n}\n\n/**\n * Declares a condition users can create an alert on (in the app's alert dialog). It does not send an alert itself.\n * @param condition - Series that is true (non-zero) on the bars where the alert fires.\n * @param title - Name of the condition in the alert dialog.\n * @param message - Default text of the alert. Default: the title.\n * @example\n * ```js\n * const cross = ta.crossover(close, ta.sma(close, 50));\n * alertcondition(cross, \"Price above SMA 50\", \"Close crossed above its 50-bar average\");\n * ```\n */\nexport function alertcondition(condition: Series, title: string, message?: string): void {\n const c = collector();\n const id = `alert${c.alertConfig.length}`;\n c.alertConfig.push({ id, title, message });\n const values = condition.toArray();\n const b = ctxBars.bars;\n const times: number[] = [];\n for (let i = 0; i < values.length && i < b.length; i++) {\n const v = values[i]!;\n if (!isNA(v) && v !== 0) times.push(b[i]!.time as number);\n }\n const last = values.length ? values[values.length - 1]! : NaN;\n c.alerts.push({ id, title, message, triggered: !isNA(last) && last !== 0, times });\n}\n\nconst ALERT_FREQUENCIES: readonly AlertFrequency[] = ['all', 'once_per_bar', 'once_per_bar_close'];\n\n/**\n * PineScript `alert(message, freq)`, with the `alert.freq_*` constants: the calls are collected per bar with their\n * message and frequency (`result.alertCalls`) for the host's alert engine, which fires the ones made on the realtime\n * bar. Called inside eachBar() / strategy.eachBar() it is a call on the current bar; at the top level of the script\n * (which PineScript runs on every bar) it is a call on every bar, `message` then being a text or one text per bar\n * (a bar whose text is na makes no call). Default frequency: `alert.freq_once_per_bar`.\n */\nfunction alertImpl(message: string | ReadonlyArray<string | undefined>, freq: AlertFrequency = 'once_per_bar'): void {\n const c = collector();\n if (!ALERT_FREQUENCIES.includes(freq)) {\n throw new Error(`alert(): freq must be alert.freq_all, alert.freq_once_per_bar or alert.freq_once_per_bar_close, not ${String(freq)}.`);\n }\n c.hasAlertFunction = true;\n const b = ctxBars.bars;\n const textAt = (i: number): string | undefined => (typeof message === 'string' ? message : message[i]);\n const call = (i: number): void => {\n const text = textAt(i);\n if (text === undefined || text === null) return;\n c.alertCalls.push({ time: b[i]!.time as number, message: String(text), freq });\n };\n if (currentBar >= 0) call(currentBar);\n else for (let i = 0; i < b.length; i++) call(i);\n}\n\nconst alertMembers = Object.assign(alertImpl, {\n freq_all: 'all',\n freq_once_per_bar: 'once_per_bar',\n freq_once_per_bar_close: 'once_per_bar_close',\n} as const);\n/**\n * Sends an alert message while the script runs (to the alerts set on the script), with the `alert.freq_*`\n * constants for how often it may fire.\n * @example\n * ```js\n * eachBar((c) => {\n * if (c.get(close) > c.get(high, 1)) alert(\"New high\", alert.freq_once_per_bar_close);\n * });\n * ```\n */\nexport const alert: AlertApi = alertMembers;\nsameKeys<typeof alertMembers, AlertApi>(true);\n\n// \u2500\u2500 Logs (log.info / log.warning / log.error) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The level of a log message. */\nexport type LogLevel = 'info' | 'warning' | 'error';\n\n/** One log.*() message: the bar it was made on (index, and time as given in the input bars), its level and text, and\n * the line of the script that made it when the host resolves it ({@link setLogLineResolver}). */\nexport interface LogEntry {\n bar: number;\n time: number;\n level: LogLevel;\n message: string;\n line?: number;\n}\n\n/** The most messages a run keeps: the newest ones. */\nexport const MAX_LOG_ENTRIES = 10_000;\n\nlet logLineResolver: ((stack: string) => number | undefined) | null = null;\n\n/**\n * Host-side: how the host finds the line of the script that called log.*(). Scripts never call it.\n * @param resolver - Gets the stack of the call (an Error's `stack`) and gives the line in the script's own source;\n * null (the default): messages have no line.\n */\nexport function setLogLineResolver(resolver: ((stack: string) => number | undefined) | null): void {\n logLineResolver = resolver;\n}\n\nfunction logImpl(level: LogLevel, message: string | ReadonlyArray<string | undefined>, args: unknown[]): void {\n const c = collector();\n const b = ctxBars.bars;\n const line = logLineResolver ? logLineResolver(new Error().stack ?? '') : undefined;\n const add = (i: number): void => {\n const text = typeof message === 'string' ? message : message[i];\n if (text === undefined || text === null) return;\n // A Series argument gives its value on the bar.\n const values = args.map((a) => (a instanceof Series ? a.get(i) : a));\n const entry: LogEntry = {\n bar: i,\n time: b[i]!.time as number,\n level,\n message: args.length ? formatMessage(String(text), values, exchangeTimezone) : String(text),\n };\n if (line !== undefined) entry.line = line;\n c.logs.push(entry);\n };\n if (currentBar >= 0) add(currentBar);\n else for (let i = 0; i < b.length; i++) add(i);\n if (c.logs.length > MAX_LOG_ENTRIES * 2) c.logs.splice(0, c.logs.length - MAX_LOG_ENTRIES);\n}\n\nconst logMembers = strictNamespace('log', {\n info(message: string | ReadonlyArray<string | undefined>, ...args: unknown[]): void {\n logImpl('info', message, args);\n },\n warning(message: string | ReadonlyArray<string | undefined>, ...args: unknown[]): void {\n logImpl('warning', message, args);\n },\n error(message: string | ReadonlyArray<string | undefined>, ...args: unknown[]): void {\n logImpl('error', message, args);\n },\n});\n/**\n * Messages for the logs panel: `log.info`, `log.warning` and `log.error`. Inside `eachBar()` a call makes a message on\n * the current bar; at the top level, one message per bar. With arguments the message is a `str.format()` pattern.\n * @example\n * ```js\n * eachBar((c) => {\n * if (c.get(volume) > 2 * c.get(ta.sma(volume, 20))) log.info(\"Volume spike: {0}\", c.get(volume));\n * });\n * ```\n */\nexport const log: LogNamespace = logMembers;\nsameKeys<typeof logMembers, LogNamespace>(true);\n\n/** The messages of a resumed run calculated from bar `from`: those of the run before on the bars before `from`, then the\n * new ones on the bars from `from` (the top-level log calls of a resumed run make them again on every bar). */\nfunction resumedLogs(before: LogEntry[] | undefined, now: LogEntry[] | undefined, from: number): LogEntry[] | undefined {\n const kept = (before ?? []).filter((e) => e.bar < from);\n const logs = kept.concat((now ?? []).filter((e) => e.bar >= from));\n return logs.length ? logs.slice(-MAX_LOG_ENTRIES) : undefined;\n}\n\n// \u2500\u2500 Convenience re-exports \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport { Series, BarData };\nexport { STRATEGY_DEFAULTS } from '../strategy/index.js';\nexport type {\n StrategyCloseAllOptions,\n StrategyCloseOptions,\n StrategyCommissionType,\n StrategyDirection,\n StrategyEngine,\n StrategyEntryOptions,\n StrategyExitOptions,\n StrategyNumberVariable,\n StrategyOcaType,\n StrategyOptions,\n StrategyProperties,\n StrategyQtyType,\n StrategyRiskDirection,\n StrategyRiskRule,\n StrategyRiskValueType,\n StrategyTextVariable,\n StrategyTrade,\n StrategyVariable,\n} from '../strategy/index.js';\n\nconst { saveRandom: _saveRandom, restoreRandom: _restoreRandom, ...mathScript } = mathCore;\nvoid _saveRandom;\nvoid _restoreRandom;\n/**\n * Math functions and constants for numbers and Series: rounding, min and max, powers and logarithms, trigonometry,\n * random numbers, `math.pi`... A Series argument gives a Series, numbers give a number. `math.round_to_mintick`\n * uses the symbol's tick size.\n * @example\n * ```js\n * const range = math.abs(close.sub(open));\n * plot(math.round(ta.sma(range, 10), 2), \"Body\");\n * ```\n */\nexport const math: Omit<typeof mathCore, 'saveRandom' | 'restoreRandom'> = strictNamespace('math', {\n ...mathScript,\n // the generators start again on each run: a resumed run would draw other numbers (#206)\n random: ((min?: number, max?: number, seed?: number) => {\n incremental.nonIncremental('math.random');\n return mathCore.random(min, max, seed);\n }) as typeof mathCore.random,\n round_to_mintick: ((number: number | Series, mintick?: number) => {\n const tick = mintick ?? syminfo.mintick;\n return number instanceof Series ? mathCore.round_to_mintick(number, tick) : mathCore.round_to_mintick(number, tick);\n }) as typeof mathCore.round_to_mintick,\n});\n// \u2500\u2500 calc: plain-English names \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** A number as a Series of the bars of the run. */\nconst asSeries = (v: Series | number): Series => (typeof v === 'number' ? Series.constant(ctxBars, v) : v);\n\n/** The kinds of `calc.average()`. */\nconst AVERAGE_KINDS: Record<string, (s: Series, n: number) => Series> = {\n simple: (s, n) => taSeries.sma(s, n),\n exponential: (s, n) => taSeries.ema(s, n),\n weighted: (s, n) => taSeries.wma(s, n),\n smoothed: (s, n) => taSeries.rma(s, n),\n hull: (s, n) => taSeries.hma(s, n),\n 'volume-weighted': (s, n) => ta.vwma(s, n),\n};\n\nfunction checkLength(fn: string, length: unknown): number {\n if (typeof length !== 'number' || !Number.isInteger(length) || length < 1) {\n throw new ScriptError(`calc.${fn}(): the length is a whole number of bars, 1 or more, got ${shown(length)}.`);\n }\n return length;\n}\n\n/** The conditions of `calc.all()` / `calc.any()` as Series; at least one is needed. */\nfunction conditionsOf(name: string, conditions: Array<Series | number>): Series[] {\n if (!conditions.length) throw new ScriptError(`${name}(): give at least one condition, e.g. ${name}(close.gt(open), volume.gt(0)).`);\n return conditions.map(asSeries);\n}\n\nconst calcMembers = strictNamespace('calc', outsideBarLoops({\n /** Moving average of the last `length` values: kind 'simple' (default), 'exponential', 'weighted', 'smoothed', 'hull' or 'volume-weighted'. */\n average(source: Series | number, length: number, kind: string = 'simple'): Series {\n const fn = AVERAGE_KINDS[kind];\n if (!fn) throw new ScriptError(`calc.average(): the kind is one of ${Object.keys(AVERAGE_KINDS).map((k) => `'${k}'`).join(', ')}, got ${shown(kind)}.`);\n return fn(asSeries(source), checkLength('average', length));\n },\n /** 1 on the bar where `a` crosses above `b`. */\n crossesAbove: (a: Series | number, b: Series | number): Series => ta.crossover(asSeries(a), b),\n /** 1 on the bar where `a` crosses below `b`. */\n crossesBelow: (a: Series | number, b: Series | number): Series => ta.crossunder(asSeries(a), b),\n /** 1 on the bar where `a` and `b` cross, either way. */\n crosses: (a: Series | number, b: Series | number): Series => ta.cross(asSeries(a), asSeries(b)),\n /** 1 where `a` is above `b`. */\n above: (a: Series | number, b: Series | number): Series => asSeries(a).gt(b),\n /** 1 where `a` is below `b`. */\n below: (a: Series | number, b: Series | number): Series => asSeries(a).lt(b),\n /** 1 where `value` is between `low` and `high` (both included). */\n between: (value: Series | number, lowLimit: Series | number, highLimit: Series | number): Series =>\n asSeries(value).gte(lowLimit).and(asSeries(value).lte(highLimit)),\n /** The value `bars` bars before (1: the previous bar). */\n previous: (source: Series | number, bars: number = 1): Series => asSeries(source).offset(checkLength('previous', bars)),\n /** The difference with the value `bars` bars before. */\n change: (source: Series | number, bars: number = 1): Series => taSeries.change(asSeries(source), checkLength('change', bars)),\n /** The change in percent since `bars` bars before. */\n percentChange: (source: Series | number, bars: number = 1): Series => {\n const s = asSeries(source);\n const before = s.offset(checkLength('percentChange', bars));\n return s.sub(before).div(before).mul(100);\n },\n /** The highest value of the last `length` bars. */\n highest: (source: Series | number, length: number): Series => ta.highest(asSeries(source), checkLength('highest', length)),\n /** The lowest value of the last `length` bars. */\n lowest: (source: Series | number, length: number): Series => ta.lowest(asSeries(source), checkLength('lowest', length)),\n /** 1 when the value rose on each of the last `bars` bars. */\n isRising: (source: Series | number, bars: number = 1): Series => taSeries.rising(asSeries(source), checkLength('isRising', bars)),\n /** 1 when the value fell on each of the last `bars` bars. */\n isFalling: (source: Series | number, bars: number = 1): Series => taSeries.falling(asSeries(source), checkLength('isFalling', bars)),\n /** Standard deviation of the last `length` values. */\n standardDeviation: (source: Series | number, length: number): Series => taSeries.stdev(asSeries(source), checkLength('standardDeviation', length)),\n /** `whenTrue` where the condition holds, else `whenFalse`. */\n ifElse: (condition: Series | number, whenTrue: Series | number, whenFalse: Series | number): Series => asSeries(condition).iff(whenTrue, whenFalse),\n /** 1 where every condition holds. */\n all: (...conditions: Array<Series | number>): Series => conditionsOf('calc.all', conditions).reduce((x, y) => x.and(y)),\n /** 1 where one of the conditions holds. */\n any: (...conditions: Array<Series | number>): Series => conditionsOf('calc.any', conditions).reduce((x, y) => x.or(y)),\n}, 'calc'));\n/**\n * Plain-English names for the most used calculations (`calc.average`, `calc.crossesAbove`...), beside the `ta.*` ones.\n * They take Series or numbers and give a Series; a condition gives 1 where true and 0 where false.\n */\nexport const calc: CalcNamespace = calcMembers;\nsameKeys<typeof calcMembers, CalcNamespace>(true);\n\n/**\n * Comparisons of two numbers with a tolerance of 1e-10 (`compare.eq(0.1 + 0.2, 0.3)` is true), for the plain numbers\n * of a bar loop.\n */\nexport const compare = compareCore;\nexport { isInputActive } from '../runtime/input-active.js';\nexport type {\n Bar,\n IndicatorResult,\n TimeValue,\n InputConfig,\n InputCondition,\n PlotConfig,\n HLineConfig,\n FillConfig,\n ShapeConfig,\n ArrowConfig,\n BarColorConfig,\n CandleConfig,\n MarkerData,\n MarkerPosition,\n MarkerShape,\n ArrowData,\n BarColorData,\n BgColorData,\n PlotCandleData,\n PlotBarData,\n LabelData,\n LabelStyle,\n LineDrawingData,\n BoxData,\n LinefillData,\n PolylineData,\n TableData,\n TableCellData,\n TableMergeData,\n TablePosition,\n MarkerLocation,\n MarkerSize,\n PineSize,\n ShapeStyle,\n};\n\n// \u2500\u2500 defineIndicator \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport {\n defineIndicator,\n type DefineIndicatorOptions,\n type IndicatorCalculation,\n type IndicatorDefinition,\n type IndicatorLiveRun,\n} from './define.js';\nexport { formula, evaluateFormula, FORMULA_FUNCTIONS, type FormulaVariables } from './formula.js';\nexport {\n defineIndicatorFromJson,\n indicatorBodyFromJson,\n checkIndicatorJson,\n type IndicatorJson,\n type JsonInput,\n type JsonPlot,\n type JsonLevel,\n type JsonFill,\n type JsonSignal,\n type JsonColorRule,\n} from './json.js';\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;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AEtH,KAAK,IAAI,eAA+C,aAAa,YAAY,UAAU,EAAE,OAAO,CAAC,GAAG,MAAM,EAAE,GAAG,CAAC,CAAC;AACvH,GAAG,MAAM,CAAC;AAKH,MAAM,OAAsB;AACnC,SAA4C,IAAI;AAMzC,MAAM,UAAU;",
|
|
6
6
|
"names": ["import_registry", "import_strategy", "box", "shown", "chart", "log", "bars", "inc", "fixnanValues", "nzValue", "at", "perBar", "staticColor", "j", "color", "location", "shape", "time", "open", "high", "low", "close", "ctx", "ticker", "scale", "m", "d", "h", "mi", "s", "session", "format", "timeframe", "calendar", "given", "currency", "order", "text", "line", "seed"]
|
|
7
7
|
}
|