oakscriptjs 0.11.6 → 0.11.7
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 +2 -1
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +5 -1
- package/dist/cjs/index.js.map +2 -2
- package/dist/cjs/runtime/inputs.d.ts.map +1 -1
- package/dist/cjs/runtime/inputs.js +6 -2
- package/dist/cjs/runtime/inputs.js.map +2 -2
- package/dist/cjs/script/index.d.ts.map +1 -1
- package/dist/cjs/script/index.js +7 -1
- package/dist/cjs/script/index.js.map +2 -2
- package/dist/cjs/utils/index.d.ts.map +1 -1
- package/dist/cjs/utils/index.js +13 -2
- package/dist/cjs/utils/index.js.map +2 -2
- package/dist/cjs/utils/source-resolver.d.ts +17 -0
- package/dist/cjs/utils/source-resolver.d.ts.map +1 -0
- package/dist/cjs/utils/source-resolver.js +45 -0
- package/dist/cjs/utils/source-resolver.js.map +7 -0
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +2 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/runtime/inputs.d.ts.map +1 -1
- package/dist/esm/runtime/inputs.js +8 -2
- package/dist/esm/runtime/inputs.js.map +1 -1
- package/dist/esm/script/index.d.ts.map +1 -1
- package/dist/esm/script/index.js +10 -1
- package/dist/esm/script/index.js.map +1 -1
- package/dist/esm/utils/index.d.ts.map +1 -1
- package/dist/esm/utils/index.js +18 -1
- package/dist/esm/utils/index.js.map +1 -1
- package/dist/esm/utils/source-resolver.d.ts +17 -0
- package/dist/esm/utils/source-resolver.d.ts.map +1 -0
- package/dist/esm/utils/source-resolver.js +24 -0
- package/dist/esm/utils/source-resolver.js.map +1 -0
- package/package.json +1 -1
- package/src/index.ts +2 -1
- package/src/runtime/inputs.ts +7 -2
- package/src/script/index.ts +8 -1
- package/src/utils/index.ts +15 -1
- package/src/utils/source-resolver.ts +29 -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 * as colorCore from '../color/index.js';\nimport { inputColorDefault } from '../color/parse.js';\nimport { fixnan as fixnanValues, isNA, nz } from '../utils/index.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 { resetDrawings, setDrawingBar, setDrawingLimits } from '../drawing/registry.js';\nexport { holdDrawing, releaseDrawing, varDrawing, type DrawingVariable } from '../drawing/registry.js';\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 { position } from '../types/index.js';\nimport type { ChartPoint } 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: { title: string; shortTitle?: string; overlay: boolean; precision?: number; format?: string };\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 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[]> };\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}\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 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 hasAlertFunction: boolean;\n strategy?: StrategyRun;\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>): Collector {\n return {\n title: 'Untitled',\n overlay: true,\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 hasAlertFunction: 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// \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\nlet scriptOptions: ScriptOptions = {};\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 ctxBars.setAll(barsInput);\n chartCtx = { ...chart };\n runNow = chart.now ?? Date.now();\n scriptOptions = options;\n ctx = freshCollector(inputs);\n resetDrawings();\n mathCore.resetRandom();\n missingSymbols = [];\n try {\n body();\n if (missingSymbols.length) throw new MissingSymbolDataError(missingSymbols);\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 },\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 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 ...drawingOutputs(ctxBars.bars, chartCtx.timeUnit),\n alerts: c.alerts.length ? c.alerts : undefined,\n alertCalls: c.alertCalls.length ? c.alertCalls : undefined,\n },\n hasAlertFunction: c.hasAlertFunction,\n };\n } finally {\n ctx = null;\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\nexport interface IndicatorOptions {\n shorttitle?: string;\n overlay?: boolean;\n precision?: number;\n format?: string;\n /** Lines kept before the oldest are deleted (default 50; PineScript keeps up to 5 more). */\n max_lines_count?: number;\n /** Labels kept before the oldest are deleted (default 50). */\n max_labels_count?: number;\n /** Boxes kept before the oldest are deleted (default 50). */\n max_boxes_count?: number;\n /** Polylines kept before the oldest are deleted (default 50). */\n max_polylines_count?: number;\n}\n\n/** PineScript `indicator()` \u2014 declares the script's metadata. */\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 c.overlay = options.overlay ?? true;\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}\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 (PineScript `group`, `inline`, `tooltip`, `confirm`, `display`, `active`). */\nexport interface InputOptions {\n group?: string;\n inline?: string;\n tooltip?: string;\n confirm?: boolean;\n display?: InputConfig['display'];\n /**\n * PineScript `active`: false greys the input out in the settings (it keeps its value). A boolean as in\n * PineScript (`active: showMa`), or a condition on input ids that a host can apply without running the script\n * (`active: 'ma_1'`, `active: { input: 'type', ne: 'None' }`)\n */\n active?: boolean | InputCondition;\n}\n\nexport interface NumericInputOptions extends InputOptions {\n minval?: number;\n maxval?: number;\n step?: number;\n}\n\nexport interface StringInputOptions extends InputOptions {\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 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 id = slugId(config.title, fallbackId, c.inputIds);\n c.inputConfig.push({ id, ...config });\n c.defaultInputs[id] = config.defval;\n const value = c.inputValues[id];\n return (value === undefined ? config.defval : value) as T;\n}\n\nfunction registerNumeric(type: 'int' | 'float', defval: number, title?: string, opts: NumericInputOptions = {}): number {\n const v = registerInput<unknown>(\n { type, defval, title, min: opts.minval, max: opts.maxval, step: opts.step, ...common(opts) },\n `input_${type}`\n );\n return typeof v === 'number' ? v : defval;\n}\n\n/** PineScript `input.*` \u2014 declares an input AND returns its current value. */\nexport const input = {\n int(defval: number, title?: string, opts: NumericInputOptions = {}): number {\n return Math.round(registerNumeric('int', defval, title, opts));\n },\n float(defval: number, title?: string, opts: NumericInputOptions = {}): number {\n return registerNumeric('float', defval, title, opts);\n },\n bool(defval: boolean, title?: string, opts: InputOptions = {}): boolean {\n return registerInput<boolean>({ type: 'bool', defval, title, ...common(opts) }, 'input_bool');\n },\n string(defval: string, title?: string, opts: StringInputOptions = {}): string {\n return registerInput<string>({ type: 'string', defval, title, options: opts.options, ...common(opts) }, 'input_string');\n },\n /** Multi-line text (\"\n\" between the lines), e.g. a list a script parses (#184). */\n text_area(defval: string, title?: string, opts: InputOptions = {}): string {\n return registerInput<string>({ type: 'text_area', defval, title, ...common(opts) }, 'input_text_area');\n },\n /**\n * Declares a colour input. As in PineScript, the default keeps an alpha of 2 decimals: an input default\n * `color.new(c, 90)` has the alpha byte 26 (25 in the script). A value given by the host is not changed.\n */\n color(defval: string, title?: string, opts: InputOptions = {}): string {\n return registerInput<string>({ type: 'color', defval: inputColorDefault(defval), title, ...common(opts) }, 'input_color');\n },\n /** Declares a source input and returns it as a Series. */\n source(defval: string = 'close', title?: string, opts: InputOptions = {}): Series {\n const name = registerInput<string>({ type: 'source', defval, title, ...common(opts) }, 'input_source');\n return sourceSeries(name);\n },\n /** Timeframe string (\"60\", \"1D\", \"W\"). As in PineScript, \"\" means the chart timeframe. */\n timeframe(defval: string, title?: string, opts: StringInputOptions = {}): string {\n return registerInput<string>(\n { type: 'timeframe', defval, title, options: opts.options, ...common(opts) },\n 'input_timeframe'\n );\n },\n /** Session string (\"0930-1600\", \"0930-1600:23456\"). */\n session(defval: string, title?: string, opts: StringInputOptions = {}): string {\n return registerInput<string>(\n { type: 'session', defval, title, options: opts.options, ...common(opts) },\n 'input_session'\n );\n },\n /** Ticker id (\"NASDAQ:MSFT\"), for `request.security` of another symbol (#180). */\n symbol(defval: string, title?: string, opts: StringInputOptions = {}): string {\n return registerInput<string>({ type: 'symbol', defval, title, options: opts.options, ...common(opts) }, 'input_symbol');\n },\n /** Date and time as a UNIX time in milliseconds, e.g. `input.time(timestamp('2024-01-01'), 'Start')`. */\n time(defval: number, title?: string, opts: InputOptions = {}): number {\n const v = registerInput<unknown>({ type: 'time', defval, title, ...common(opts) }, 'input_time');\n return typeof v === 'number' ? v : 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\nexport const open = Series.fromBars(ctxBars, 'open');\nexport const high = Series.fromBars(ctxBars, 'high');\nexport const low = Series.fromBars(ctxBars, 'low');\nexport const close = Series.fromBars(ctxBars, 'close');\nexport const volume = Series.fromBars(ctxBars, 'volume');\nexport const hl2 = new Series(ctxBars, (b) => (b.high + b.low) / 2);\nexport const hlc3 = new Series(ctxBars, (b) => (b.high + b.low + b.close) / 3);\nexport const ohlc4 = new Series(ctxBars, (b) => (b.open + b.high + b.low + b.close) / 4);\nexport const hlcc4 = new Series(ctxBars, (b) => (b.high + b.low + b.close + b.close) / 4);\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\nfunction sourceSeries(name: string): Series {\n return SOURCES[name] ?? close;\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/** ta.* with the chart-implicit (bars-first) functions bound to the context,\n * so scripts call them like PineScript: `ta.tr(true)`, `ta.atr(14)`. */\nexport const ta = {\n ...taSeries,\n tr: (handleNa: boolean = false): Series => taSeries.tr(bars(), handleNa),\n atr: (length: number): Series => taSeries.atr(bars(), length),\n sar: (start?: number, inc?: number, max?: number): Series => taSeries.sar(bars(), start, inc, max),\n wpr: (length?: number): Series => taSeries.wpr(bars(), length),\n supertrend: (factor: number, atrLength: number): [Series, Series] =>\n taSeries.supertrend(bars(), factor, atrLength),\n dmi: (diLength: number, adxSmoothing: number): [Series, Series, Series] =>\n 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 typeof sourceOrLength === 'number' ? taSeries.highest(high, sourceOrLength) : taSeries.highest(sourceOrLength, length!),\n /** `ta.lowest(source, length)` or `ta.lowest(length)` (source = low). */\n lowest: (sourceOrLength: Series | number, length?: number | Series): Series =>\n typeof sourceOrLength === 'number' ? taSeries.lowest(low, sourceOrLength) : taSeries.lowest(sourceOrLength, length!),\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.mfi(source, length)` with the chart volume (PineScript takes 2 arguments). */\n mfi: (source: Series, length: number): Series => 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};\n\n/** PineScript `fixnan(source)`: each `na` value becomes the previous non-`na` value.\n * Accepts a Series or a per-bar color array (`undefined` = `na`, as returned by `color.when`). */\nexport function fixnan(source: Series): Series;\nexport function fixnan(source: Array<string | undefined>): Array<string | undefined>;\nexport function fixnan(source: Series | Array<string | undefined>): Series | Array<string | undefined> {\n return source instanceof Series ? Series.fromArray(ctxBars, fixnanValues(source.toArray())) : fixnanValues(source);\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/** 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 return cond.toArray().map((v) => (!isNA(v) && v !== 0 ? colorTrue : colorFalse));\n}\n\n/** color.* plus `when` \u2014 per-bar conditional colors for plot()/fill()/bgcolor()/barcolor(). */\nexport const color = {\n ...colorCore,\n new: colorCore.new_color,\n when: colorWhen,\n};\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\nexport interface ScriptPlotOptions {\n /** Static color, or a per-bar color array from color.when(). */\n color?: string | string[];\n linewidth?: number;\n style?: PlotConfig['style'];\n /** Line style (PineScript `linestyle`); default solid. A constant or an input value, not per bar. */\n linestyle?: PlotConfig['linestyle'];\n display?: PlotConfig['display'];\n histbase?: number;\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}\n\n/** PineScript `plot()` \u2014 declares the plot and supplies its data in one call. */\nfunction plotImpl(series: Series, title?: string, options: ScriptPlotOptions = {}): PlotHandle {\n const c = collector();\n const id = `plot${c.plotConfig.length}`;\n const perBar = Array.isArray(options.color) ? options.color : undefined;\n const staticColor = typeof options.color === 'string' ? options.color : (perBar?.[perBar.length - 1] ?? '#2962FF');\n c.plotConfig.push({\n id,\n title: title ?? id,\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 });\n c.outputs.push({ kind: 'plot', id, title: title ?? id });\n const values = series.toArray();\n const b = bars();\n const data: TimeValue[] = [];\n for (let i = 0; i < b.length; i++) {\n const value = values[i];\n if (value === undefined || !Number.isFinite(value)) continue; // PineScript plots +/-Infinity as na\n data.push(perBar ? { time: b[i]!.time, value, color: perBar[i] } : { time: b[i]!.time, value });\n }\n c.plots[id] = data;\n return { id, kind: 'plot' };\n}\n\n/**\n * PineScript `plot()`, with the `plot.style_*` and `plot.linestyle_*` constants:\n * `plot(src, 'Level', { style: plot.style_stepline, linestyle: plot.linestyle_dashed })`.\n */\nexport const plot = 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 color?: string;\n /** Line style; default dashed (PineScript). */\n linestyle?: HLineConfig['linestyle'];\n linewidth?: number;\n}\n\n/** PineScript `hline()` \u2014 a static horizontal level. Default line style: dashed (PineScript). */\nfunction hlineImpl(price: number, title?: string, options: ScriptHLineOptions = {}): PlotHandle {\n const c = collector();\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 });\n return { id, kind: 'hline' };\n}\n\n/** PineScript `hline()`, with the `hline.style_*` constants: `hline(0, 'Zero', { linestyle: hline.style_dotted })`. */\nexport const hline = Object.assign(hlineImpl, {\n style_solid: 'solid',\n style_dotted: 'dotted',\n style_dashed: 'dashed',\n} as const);\n\nexport interface ScriptFillOptions {\n /** Static color, or a per-bar color array from color.when(). */\n color?: string | string[];\n title?: string;\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/**\n * PineScript `fill()`, with the three PineScript overloads (positional arguments), for two plots or two hlines:\n * - `fill(p1, p2, color?, title?, ...)`\n * - `fill(p1, p2, top_value, bottom_value, top_color, bottom_color, title?, ...)`: gradient fill; values and colours\n * can change per bar (a Series / a color.when() array)\n * - `fill(p1, p2, { color, title })`: options object (oakscriptjs form, kept for existing scripts)\n * Arguments that change only how the chart shows the fill (`editable`, `show_last`, `fillgaps`, `display`) are\n * accepted and not used.\n */\nexport function fill(a: PlotHandle, b: PlotHandle, options?: ScriptFillOptions): void;\nexport function fill(a: PlotHandle, b: PlotHandle, color: ScriptFillColor, title?: string, ...rest: unknown[]): void;\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 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 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 } 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 staticColor = typeof options.color === 'string' ? options.color : undefined;\n title = options.title;\n } else {\n const color = third as ScriptFillColor;\n perBar = Array.isArray(color) ? color.map((x) => x ?? '') : undefined;\n staticColor = typeof color === 'string' ? color : undefined;\n title = args[1] as string | undefined;\n }\n if (a.kind === 'hline' && b.kind === 'hline') {\n c.fillConfig.push({\n id: `fill${c.fillConfig.length}`,\n plot1: a.id,\n plot2: b.id,\n color: staticColor,\n colors: perBar,\n gradient,\n title,\n });\n return;\n }\n c.fills.push({\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}\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 const c = collector();\n const id = `${kind}${c.shapeConfig.filter((s) => s.kind === kind).length}`;\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 });\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\n/** PineScript `plotshape()` \u2014 a marker on each bar where the condition holds. */\nexport function plotshape(condition: Series, title?: string, options: PlotShapeOptions = {}): void {\n emitMarkers('shape', condition, title, options);\n}\n\n/** PineScript `plotchar()` \u2014 a character marker on each bar where the condition holds. */\nexport function plotchar(condition: Series, title?: string, options: PlotCharOptions = {}): void {\n emitMarkers('char', condition, title, options);\n}\n\nexport interface PlotArrowOptions {\n /** Color of the up arrows: a color or a per-bar array (default #00FF00, PineScript). */\n colorup?: string | Array<string | undefined>;\n /** Color of the down arrows: a color or a per-bar array (default #FF0000, PineScript). */\n colordown?: string | Array<string | undefined>;\n /** Display offset in bars (arrow shown at bar i + offset). */\n offset?: number;\n /** Minimal arrow height in pixels (default 5). */\n minheight?: number;\n /** Maximal arrow height in pixels (default 100). */\n maxheight?: number;\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}\n\n/**\n * PineScript `plotarrow()` \u2014 an up arrow below the bar for a positive value, a down arrow above the bar for a\n * negative value, nothing for 0 / na. The arrows go to `result.arrows` (value and color per bar), the declaration to\n * `arrowConfig`; the renderer scales the height with the absolute value between minheight and maxheight.\n */\nexport function plotarrow(series: Series, title?: string, options: PlotArrowOptions = {}): void {\n const c = collector();\n const id = `arrow${c.arrowConfig.length}`;\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 });\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 }\n): void {\n const c = collector();\n const id = `${kind}${c.barColorConfig.filter((x) => x.kind === kind).length}`;\n c.barColorConfig.push({ id, kind, title: options.title, offset: options.offset, forceOverlay: options.force_overlay });\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, forceOverlay } : { time: b[j]!.time, color: col });\n }\n}\n\n/**\n * PineScript `bgcolor()` \u2014 per-bar background color. `force_overlay: true` colors the main chart pane even when the\n * script is not an overlay.\n */\nexport function bgcolor(\n colors: string | Array<string | undefined>,\n options: { offset?: number; title?: string; force_overlay?: boolean } = {}\n): void {\n emitBarColors('bgcolor', colors, options);\n}\n\n/** PineScript `barcolor()` \u2014 per-bar candle color override. */\nexport function barcolor(\n colors: string | Array<string | undefined>,\n options: { title?: string } = {}\n): void {\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: a colour or a per-bar array (color.when); an na entry gives a transparent body */\n color?: ScriptCandleColor;\n /** Wick colour: a colour or a per-bar array */\n wickcolor?: ScriptCandleColor;\n /** Border colour: a colour or a per-bar array */\n bordercolor?: ScriptCandleColor;\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}\n\nexport interface PlotBarOptions {\n /** Bar colour: a colour or a per-bar array (color.when); an na entry gives a transparent bar */\n color?: ScriptCandleColor;\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}\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 * PineScript `plotcandle(open, high, low, close, title?, { color, wickcolor, bordercolor, display, force_overlay })`:\n * candles in `result.plotCandles[id]`, the declaration in `candleConfig`. A bar with an na value has no candle.\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 const c = collector();\n const id = `plotcandle${c.candleConfig.filter((x) => x.kind === 'candle').length}`;\n c.candleConfig.push({\n id,\n kind: 'candle',\n title,\n color: staticColor(options.color),\n wickColor: staticColor(options.wickcolor),\n borderColor: staticColor(options.bordercolor),\n display: options.display,\n forceOverlay: options.force_overlay,\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 color = candleColor(options.color, i);\n const wickColor = candleColor(options.wickcolor, i);\n const borderColor = candleColor(options.bordercolor, i);\n if (color !== undefined) candle.color = color;\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 * PineScript `plotbar(open, high, low, close, title?, { color, display, force_overlay })`: OHLC bars in\n * `result.plotBars[id]`, the declaration in `candleConfig`. A bar with an na value is not drawn.\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 const c = collector();\n const id = `plotbar${c.candleConfig.filter((x) => x.kind === 'bar').length}`;\n c.candleConfig.push({\n id,\n kind: 'bar',\n title,\n color: staticColor(options.color),\n display: options.display,\n forceOverlay: options.force_overlay,\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(options.color, 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\nexport function eachBar(fn: (c: BarContext) => number | boolean | void): Series {\n collector(); // same lifecycle guard (and error message) as the declaration calls\n const b = bars();\n const out: number[] = new Array(b.length).fill(NaN);\n const cache = new Map<Series, number[]>();\n const buffers = new Map<Series, HistoryBuffer>();\n let pendingError: { bar: number; barsBack: number } | null = null;\n let idx = 0;\n const ctx: BarContext = {\n get i() {\n return idx;\n },\n n: b.length,\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(src);\n if (!buffer) buffers.set(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 try {\n for (idx = 0; idx < b.length; idx++) {\n if (pendingError && pendingError.bar === idx) throw new Error(historyError(idx, pendingError.barsBack));\n currentBar = idx;\n setDrawingBar(idx, idx === b.length - 1, b.length - 1);\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 }\n } finally {\n currentBar = -1;\n setDrawingBar(null);\n }\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 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 return eachBar((c) => {\n engine.processBar(c.i);\n run.inLoop = true;\n try {\n return fn(c);\n } finally {\n run.inLoop = false;\n engine.processClose(c.i);\n }\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 = Object.defineProperties(\n Object.assign((title: string, options?: StrategyOptions) => declareStrategy(title, options), strategyMembers),\n variableGetters\n) as StrategyApi;\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 basecurrency?: string;\n /** Root of the symbol (PineScript `syminfo.root`): \"BTC\" for CME:BTC1!, \"ES\" for CME_MINI:ES1!, \"AAPL\" for NASDAQ:AAPL (#180) */\n root?: string;\n /** Description of the symbol (PineScript `syminfo.description`): \"Apple Inc.\" for NASDAQ:AAPL, \"Bitcoin / U.S. dollar\" for BITSTAMP:BTCUSD (#184) */\n description?: string;\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 /** 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\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>;\n\n/** A request of `request.security` for another symbol whose bars the host has not given. */\nexport interface SymbolDataRequest {\n symbol: string;\n timeframe: string;\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 super(\n `request.security needs the bars of ${requests.map((r) => `${r.symbol} (${r.timeframe})`).join(', ')}: ` +\n 'pass them with ChartContext.bars.'\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 = {\n ...timeframeCore,\n get period(): string {\n return chartTimeframe().period;\n },\n get main_period(): string {\n return 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. */\nfunction chartText(\n key: 'symbolType' | 'currency' | 'basecurrency' | 'root' | 'description' | 'foregroundColor' | 'backgroundColor',\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 return value;\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.timezone`, `syminfo.tickerid`, `syminfo.session` (session type), `syminfo.mintick`,\n * `syminfo.minmove`, `syminfo.pricescale`, `syminfo.pointvalue`, `syminfo.mincontract`, `syminfo.type`,\n * `syminfo.currency`, `syminfo.basecurrency`, `syminfo.root` and `syminfo.description`, from the chart context.\n */\nexport const syminfo = {\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 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 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 return chartText('root', 'syminfo.root');\n },\n get description(): string {\n return chartText('description', 'syminfo.description');\n },\n};\n\n/** A calendar function: `(time, timezone?)` on a UNIX time or on a Series of times. */\ninterface CalendarFunction {\n (time: number, timezone?: string): number;\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/** PineScript `year(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const year = calendar(timeCore.year);\n/** PineScript `month(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const month = calendar(timeCore.month);\n/** PineScript `weekofyear(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const weekofyear = calendar(timeCore.weekofyear);\n/** PineScript `dayofmonth(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const dayofmonth = calendar(timeCore.dayofmonth);\n/** PineScript `dayofweek(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const dayofweek = calendar(timeCore.dayofweek);\n/** PineScript `hour(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const hour = calendar(timeCore.hour);\n/** PineScript `minute(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const minute = calendar(timeCore.minute);\n/** PineScript `second(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const second = calendar(timeCore.second);\n\n/**\n * PineScript `timestamp`: date string (GMT+0 by default), `(timezone, year, month, day, ...)`, or\n * `(year, month, day, ...)` in the exchange time zone.\n */\nexport function timestamp(dateString: string): number;\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;\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/** Session test of PineScript `time(timeframe, session, timezone)`; the default time zone is the exchange time zone. */\nexport function inSession(time: number, session: string, timezone?: string): boolean {\n return timeCore.inSession(time, session, timezone ?? exchangeTimezone());\n}\n\n/** PineScript `str.*`; `format_time` and the dates of `format` use the exchange time zone by default. */\nexport const 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 format_time(time: number, format: string = \"yyyy-MM-dd'T'HH:mm:ssZ\", timezone?: string): string {\n return strCore.format_time(time, format, timezone ?? exchangeTimezone());\n },\n format(pattern: string, ...args: unknown[]): string {\n return formatMessage(pattern, args, exchangeTimezone);\n },\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\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\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/**\n * PineScript `time`: the bar open time in ms (a Series), and `time(timeframe?, session?, timezone?)`:\n * the open time of the `timeframe` period that contains the bar, `na` outside `session`.\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, () => runNow);\n\nexport const time = callableSeries(new Series(ctxBars, (b) => barTime(b)), timeFunction);\n\n/**\n * PineScript `time_close`: the bar close time in ms (a Series), and `time_close(timeframe?, session?, timezone?)`.\n * Needs the chart timeframe and session.\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\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 = {\n get isfirst(): Series { return barFlag((i) => i === 0); },\n get islast(): Series { return barFlag((i, n) => i === n - 1); },\n get isconfirmed(): Series { return barFlag((i, n) => i < n - 1 || chartCtx.lastBarConfirmed === true); },\n get isrealtime(): Series { return barFlag(lastRealtime); },\n get ishistory(): Series { return barFlag((i, n) => !lastRealtime(i, n)); },\n get isnew(): Series { return barFlag((i, n) => !lastRealtime(i, n) || chartCtx.lastBarNew !== false); },\n get islastconfirmedhistory(): Series {\n return barFlag((i, n) => {\n const lastConfirmed = chartCtx.lastBarConfirmed === true && chartCtx.realtime !== true;\n return i === (lastConfirmed ? n - 1 : n - 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 = {\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 = {\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 = {\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 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 if (timeframeCore.in_seconds(tf) < timeframeCore.in_seconds(chart.period)) {\n // a lower timeframe of the chart symbol: its bars come from ChartContext.bars (#181)\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.calendar.locate(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 };\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\n chartCtx = {\n ...chartCtx,\n tickerid: symbol,\n timeframe: tf,\n timezone: info.timezone,\n session: info.session,\n regularSession: info.regularSession,\n mintick: info.mintick,\n minmove: info.minmove,\n pricescale: info.pricescale,\n pointvalue: info.pointvalue,\n mincontract: info.mincontract,\n symbolType: info.symbolType,\n currency: info.currency,\n basecurrency: info.basecurrency,\n root: info.root,\n description: info.description,\n };\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 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/** PineScript `request.*`: `security` (issue #101, other symbols #179, lower timeframes #181) and `security_lower_tf`. */\nexport const request = { security, security_lower_tf };\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. */\nexport const line = {\n ...lineCore,\n get all() {\n return lineCore.all();\n },\n};\n\n/** PineScript `label.*`; `label.all` lists the live labels in creation order. */\nexport const label = {\n ...labelCore,\n get all() {\n return labelCore.all();\n },\n};\n\n/** PineScript `box.*`; `box.all` lists the live boxes in creation order. */\nexport const box = {\n ...boxCore,\n get all() {\n return boxCore.all();\n },\n};\n\n/** PineScript `linefill.*`; `linefill.all` lists the live linefills in creation order. */\nexport const linefill = {\n ...linefillCore,\n get all() {\n return linefillCore.all();\n },\n};\n\n/** PineScript `polyline.*`; `polyline.all` lists the live polylines in creation order. */\nexport const polyline = {\n ...polylineCore,\n get all() {\n return polylineCore.all();\n },\n};\n\n/**\n * PineScript `table.*`; `table.all` lists the live tables in creation order. The live tables go to `result.tables`.\n */\nexport const table = {\n ...tableCore,\n get all() {\n return tableCore.all();\n },\n};\n\n/** PineScript `position.*` constants (table positions). */\nexport { position };\n\n/** PineScript `text.format_*`, `text.align_*` and `text.wrap_*` constants. */\nexport const text = { ...textCore };\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 = {\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 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/** Wraps a plain value array (e.g. a side output accumulated inside eachBar)\n * into a Series aligned with the current bars. */\nexport function seriesOf(values: number[]): Series {\n collector();\n return Series.fromArray(ctxBars, values);\n}\n\n/** PineScript `alertcondition()` \u2014 collected for the host's alert engine. */\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\n/** PineScript `alert()` with the `alert.freq_*` constants: `alert('Crossed', alert.freq_once_per_bar_close)`. */\nexport const alert = 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// \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, isNA as na, nz };\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\n/** PineScript `math.*`; `math.round_to_mintick(x)` uses `syminfo.mintick` of the chart context. */\nexport const math = {\n ...mathCore,\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};\nexport * as compare from '../compare/index.js';\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"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2EA,oBAA6D;AAC7D,eAA0B;AAC1B,gBAA2B;AAC3B,mBAAkC;AAClC,mBAAiD;AACjD,eAA0B;AAC1B,gBAA2B;AAC3B,cAAyB;AACzB,mBAA8B;AAC9B,mBAA8B;AAC9B,gBAA2B;AAC3B,qBAAgC;AAChC,eAA0B;AAC1B,eAA0B;AAC1B,sBAA+D;AAC/D,IAAAA,mBAA8E;AAC9E,oBAA+B;AAC/B,oBAA+B;AAC/B,eAA0B;AAC1B,cAAyB;AACzB,2BAA8B;AAC9B,0BAA0B;AAC1B,sBAAkD;AAClD,kBAA2E;AAC3E,sBAA6E;AAC7E,mBAAsE;AACtE,mBAAyB;AAEzB,sBAoBO;AACP,qBAAo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AoB;AASjG,SAAS,UAAU,SAAqD,OAAuB,gBAAsB;AACnH,QAAM,IAAI,UAAU;AACpB,MAAI,CAAC,kBAAkB,SAAS,IAAI,GAAG;AACrC,UAAM,IAAI,MAAM,uGAAuG,OAAO,IAAI,CAAC,GAAG;AAAA,EACxI;AACA,IAAE,mBAAmB;AACrB,QAAM,IAAI,QAAQ;AAClB,QAAM,SAAS,CAAC,MAAmC,OAAO,YAAY,WAAW,UAAU,QAAQ,CAAC;AACpG,QAAM,OAAO,CAAC,MAAoB;AAChC,UAAMK,QAAO,OAAO,CAAC;AACrB,QAAIA,UAAS,UAAaA,UAAS,KAAM;AACzC,MAAE,WAAW,KAAK,EAAE,MAAM,EAAE,CAAC,EAAG,MAAgB,SAAS,OAAOA,KAAI,GAAG,KAAK,CAAC;AAAA,EAC/E;AACA,MAAI,cAAc,EAAG,MAAK,UAAU;AAAA,MAC/B,UAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,IAAK,MAAK,CAAC;AAChD;AAGO,MAAM,QAAQ,OAAO,OAAO,WAAW;AAAA,EAC5C,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB,yBAAyB;AAC3B,CAAU;AA4BH,MAAM,OAAO;AAAA,EAClB,GAAG;AAAA,EACH,mBAAmB,CAAC,QAAyB,YAAqB;AAChE,UAAM,OAAO,WAAW,QAAQ;AAChC,WAAO,kBAAkB,uBAAS,SAAS,iBAAiB,QAAQ,IAAI,IAAI,SAAS,iBAAiB,QAAQ,IAAI;AAAA,EACpH;AACF;",
|
|
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 * as colorCore from '../color/index.js';\nimport { inputColorDefault } from '../color/parse.js';\nimport { fixnan as fixnanValues, isNA, nz } 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 { resetDrawings, setDrawingBar, setDrawingLimits } from '../drawing/registry.js';\nexport { holdDrawing, releaseDrawing, varDrawing, type DrawingVariable } from '../drawing/registry.js';\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 { position } from '../types/index.js';\nimport type { ChartPoint } 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: { title: string; shortTitle?: string; overlay: boolean; precision?: number; format?: string };\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 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[]> };\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}\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 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 hasAlertFunction: boolean;\n strategy?: StrategyRun;\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>): Collector {\n return {\n title: 'Untitled',\n overlay: true,\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 hasAlertFunction: 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// \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\nlet scriptOptions: ScriptOptions = {};\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 ctxBars.setAll(barsInput);\n chartCtx = { ...chart };\n runNow = chart.now ?? Date.now();\n scriptOptions = options;\n ctx = freshCollector(inputs);\n resetDrawings();\n mathCore.resetRandom();\n missingSymbols = [];\n try {\n body();\n if (missingSymbols.length) throw new MissingSymbolDataError(missingSymbols);\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 },\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 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 ...drawingOutputs(ctxBars.bars, chartCtx.timeUnit),\n alerts: c.alerts.length ? c.alerts : undefined,\n alertCalls: c.alertCalls.length ? c.alertCalls : undefined,\n },\n hasAlertFunction: c.hasAlertFunction,\n };\n } finally {\n ctx = null;\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\nexport interface IndicatorOptions {\n shorttitle?: string;\n overlay?: boolean;\n precision?: number;\n format?: string;\n /** Lines kept before the oldest are deleted (default 50; PineScript keeps up to 5 more). */\n max_lines_count?: number;\n /** Labels kept before the oldest are deleted (default 50). */\n max_labels_count?: number;\n /** Boxes kept before the oldest are deleted (default 50). */\n max_boxes_count?: number;\n /** Polylines kept before the oldest are deleted (default 50). */\n max_polylines_count?: number;\n}\n\n/** PineScript `indicator()` \u2014 declares the script's metadata. */\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 c.overlay = options.overlay ?? true;\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}\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 (PineScript `group`, `inline`, `tooltip`, `confirm`, `display`, `active`). */\nexport interface InputOptions {\n group?: string;\n inline?: string;\n tooltip?: string;\n confirm?: boolean;\n display?: InputConfig['display'];\n /**\n * PineScript `active`: false greys the input out in the settings (it keeps its value). A boolean as in\n * PineScript (`active: showMa`), or a condition on input ids that a host can apply without running the script\n * (`active: 'ma_1'`, `active: { input: 'type', ne: 'None' }`)\n */\n active?: boolean | InputCondition;\n}\n\nexport interface NumericInputOptions extends InputOptions {\n minval?: number;\n maxval?: number;\n step?: number;\n}\n\nexport interface StringInputOptions extends InputOptions {\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 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 id = slugId(config.title, fallbackId, c.inputIds);\n c.inputConfig.push({ id, ...config });\n c.defaultInputs[id] = config.defval;\n const value = c.inputValues[id];\n return (value === undefined ? config.defval : value) as T;\n}\n\nfunction registerNumeric(type: 'int' | 'float', defval: number, title?: string, opts: NumericInputOptions = {}): number {\n const v = registerInput<unknown>(\n { type, defval, title, min: opts.minval, max: opts.maxval, step: opts.step, ...common(opts) },\n `input_${type}`\n );\n return typeof v === 'number' ? v : defval;\n}\n\n/** PineScript `input.*` \u2014 declares an input AND returns its current value. */\nexport const input = {\n int(defval: number, title?: string, opts: NumericInputOptions = {}): number {\n return Math.round(registerNumeric('int', defval, title, opts));\n },\n float(defval: number, title?: string, opts: NumericInputOptions = {}): number {\n return registerNumeric('float', defval, title, opts);\n },\n bool(defval: boolean, title?: string, opts: InputOptions = {}): boolean {\n return registerInput<boolean>({ type: 'bool', defval, title, ...common(opts) }, 'input_bool');\n },\n string(defval: string, title?: string, opts: StringInputOptions = {}): string {\n return registerInput<string>({ type: 'string', defval, title, options: opts.options, ...common(opts) }, 'input_string');\n },\n /** Multi-line text (\"\n\" between the lines), e.g. a list a script parses (#184). */\n text_area(defval: string, title?: string, opts: InputOptions = {}): string {\n return registerInput<string>({ type: 'text_area', defval, title, ...common(opts) }, 'input_text_area');\n },\n /**\n * Declares a colour input. As in PineScript, the default keeps an alpha of 2 decimals: an input default\n * `color.new(c, 90)` has the alpha byte 26 (25 in the script). A value given by the host is not changed.\n */\n color(defval: string, title?: string, opts: InputOptions = {}): string {\n return registerInput<string>({ type: 'color', defval: inputColorDefault(defval), title, ...common(opts) }, 'input_color');\n },\n /** Declares a source input and returns it as a Series. */\n source(defval: string = 'close', title?: string, opts: InputOptions = {}): Series {\n const name = registerInput<string>({ type: 'source', defval, title, ...common(opts) }, 'input_source');\n return sourceSeries(name);\n },\n /** Timeframe string (\"60\", \"1D\", \"W\"). As in PineScript, \"\" means the chart timeframe. */\n timeframe(defval: string, title?: string, opts: StringInputOptions = {}): string {\n return registerInput<string>(\n { type: 'timeframe', defval, title, options: opts.options, ...common(opts) },\n 'input_timeframe'\n );\n },\n /** Session string (\"0930-1600\", \"0930-1600:23456\"). */\n session(defval: string, title?: string, opts: StringInputOptions = {}): string {\n return registerInput<string>(\n { type: 'session', defval, title, options: opts.options, ...common(opts) },\n 'input_session'\n );\n },\n /** Ticker id (\"NASDAQ:MSFT\"), for `request.security` of another symbol (#180). */\n symbol(defval: string, title?: string, opts: StringInputOptions = {}): string {\n return registerInput<string>({ type: 'symbol', defval, title, options: opts.options, ...common(opts) }, 'input_symbol');\n },\n /** Date and time as a UNIX time in milliseconds, e.g. `input.time(timestamp('2024-01-01'), 'Start')`. */\n time(defval: number, title?: string, opts: InputOptions = {}): number {\n const v = registerInput<unknown>({ type: 'time', defval, title, ...common(opts) }, 'input_time');\n return typeof v === 'number' ? v : 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\nexport const open = Series.fromBars(ctxBars, 'open');\nexport const high = Series.fromBars(ctxBars, 'high');\nexport const low = Series.fromBars(ctxBars, 'low');\nexport const close = Series.fromBars(ctxBars, 'close');\nexport const volume = Series.fromBars(ctxBars, 'volume');\nexport const hl2 = new Series(ctxBars, (b) => (b.high + b.low) / 2);\nexport const hlc3 = new Series(ctxBars, (b) => (b.high + b.low + b.close) / 3);\nexport const ohlc4 = new Series(ctxBars, (b) => (b.open + b.high + b.low + b.close) / 4);\nexport const hlcc4 = new Series(ctxBars, (b) => (b.high + b.low + b.close + b.close) / 4);\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\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/** ta.* with the chart-implicit (bars-first) functions bound to the context,\n * so scripts call them like PineScript: `ta.tr(true)`, `ta.atr(14)`. */\nexport const ta = {\n ...taSeries,\n tr: (handleNa: boolean = false): Series => taSeries.tr(bars(), handleNa),\n atr: (length: number): Series => taSeries.atr(bars(), length),\n sar: (start?: number, inc?: number, max?: number): Series => taSeries.sar(bars(), start, inc, max),\n wpr: (length?: number): Series => taSeries.wpr(bars(), length),\n supertrend: (factor: number, atrLength: number): [Series, Series] =>\n taSeries.supertrend(bars(), factor, atrLength),\n dmi: (diLength: number, adxSmoothing: number): [Series, Series, Series] =>\n 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 typeof sourceOrLength === 'number' ? taSeries.highest(high, sourceOrLength) : taSeries.highest(sourceOrLength, length!),\n /** `ta.lowest(source, length)` or `ta.lowest(length)` (source = low). */\n lowest: (sourceOrLength: Series | number, length?: number | Series): Series =>\n typeof sourceOrLength === 'number' ? taSeries.lowest(low, sourceOrLength) : taSeries.lowest(sourceOrLength, length!),\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.mfi(source, length)` with the chart volume (PineScript takes 2 arguments). */\n mfi: (source: Series, length: number): Series => 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};\n\n/** PineScript `fixnan(source)`: each `na` value becomes the previous non-`na` value.\n * Accepts a Series or a per-bar color array (`undefined` = `na`, as returned by `color.when`). */\nexport function fixnan(source: Series): Series;\nexport function fixnan(source: Array<string | undefined>): Array<string | undefined>;\nexport function fixnan(source: Series | Array<string | undefined>): Series | Array<string | undefined> {\n return source instanceof Series ? Series.fromArray(ctxBars, fixnanValues(source.toArray())) : fixnanValues(source);\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/** 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 return cond.toArray().map((v) => (!isNA(v) && v !== 0 ? colorTrue : colorFalse));\n}\n\n/** color.* plus `when` \u2014 per-bar conditional colors for plot()/fill()/bgcolor()/barcolor(). */\nexport const color = {\n ...colorCore,\n new: colorCore.new_color,\n when: colorWhen,\n};\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\nexport interface ScriptPlotOptions {\n /** Static color, or a per-bar color array from color.when(). */\n color?: string | string[];\n linewidth?: number;\n style?: PlotConfig['style'];\n /** Line style (PineScript `linestyle`); default solid. A constant or an input value, not per bar. */\n linestyle?: PlotConfig['linestyle'];\n display?: PlotConfig['display'];\n histbase?: number;\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}\n\n/** PineScript `plot()` \u2014 declares the plot and supplies its data in one call. */\nfunction plotImpl(series: Series, title?: string, options: ScriptPlotOptions = {}): PlotHandle {\n const c = collector();\n const id = `plot${c.plotConfig.length}`;\n const perBar = Array.isArray(options.color) ? options.color : undefined;\n const staticColor = typeof options.color === 'string' ? options.color : (perBar?.[perBar.length - 1] ?? '#2962FF');\n c.plotConfig.push({\n id,\n title: title ?? id,\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 });\n c.outputs.push({ kind: 'plot', id, title: title ?? id });\n const values = series.toArray();\n const b = bars();\n const data: TimeValue[] = [];\n for (let i = 0; i < b.length; i++) {\n const value = values[i];\n if (value === undefined || !Number.isFinite(value)) continue; // PineScript plots +/-Infinity as na\n data.push(perBar ? { time: b[i]!.time, value, color: perBar[i] } : { time: b[i]!.time, value });\n }\n c.plots[id] = data;\n return { id, kind: 'plot' };\n}\n\n/**\n * PineScript `plot()`, with the `plot.style_*` and `plot.linestyle_*` constants:\n * `plot(src, 'Level', { style: plot.style_stepline, linestyle: plot.linestyle_dashed })`.\n */\nexport const plot = 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 color?: string;\n /** Line style; default dashed (PineScript). */\n linestyle?: HLineConfig['linestyle'];\n linewidth?: number;\n}\n\n/** PineScript `hline()` \u2014 a static horizontal level. Default line style: dashed (PineScript). */\nfunction hlineImpl(price: number, title?: string, options: ScriptHLineOptions = {}): PlotHandle {\n const c = collector();\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 });\n return { id, kind: 'hline' };\n}\n\n/** PineScript `hline()`, with the `hline.style_*` constants: `hline(0, 'Zero', { linestyle: hline.style_dotted })`. */\nexport const hline = Object.assign(hlineImpl, {\n style_solid: 'solid',\n style_dotted: 'dotted',\n style_dashed: 'dashed',\n} as const);\n\nexport interface ScriptFillOptions {\n /** Static color, or a per-bar color array from color.when(). */\n color?: string | string[];\n title?: string;\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/**\n * PineScript `fill()`, with the three PineScript overloads (positional arguments), for two plots or two hlines:\n * - `fill(p1, p2, color?, title?, ...)`\n * - `fill(p1, p2, top_value, bottom_value, top_color, bottom_color, title?, ...)`: gradient fill; values and colours\n * can change per bar (a Series / a color.when() array)\n * - `fill(p1, p2, { color, title })`: options object (oakscriptjs form, kept for existing scripts)\n * Arguments that change only how the chart shows the fill (`editable`, `show_last`, `fillgaps`, `display`) are\n * accepted and not used.\n */\nexport function fill(a: PlotHandle, b: PlotHandle, options?: ScriptFillOptions): void;\nexport function fill(a: PlotHandle, b: PlotHandle, color: ScriptFillColor, title?: string, ...rest: unknown[]): void;\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 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 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 } 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 staticColor = typeof options.color === 'string' ? options.color : undefined;\n title = options.title;\n } else {\n const color = third as ScriptFillColor;\n perBar = Array.isArray(color) ? color.map((x) => x ?? '') : undefined;\n staticColor = typeof color === 'string' ? color : undefined;\n title = args[1] as string | undefined;\n }\n if (a.kind === 'hline' && b.kind === 'hline') {\n c.fillConfig.push({\n id: `fill${c.fillConfig.length}`,\n plot1: a.id,\n plot2: b.id,\n color: staticColor,\n colors: perBar,\n gradient,\n title,\n });\n return;\n }\n c.fills.push({\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}\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 const c = collector();\n const id = `${kind}${c.shapeConfig.filter((s) => s.kind === kind).length}`;\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 });\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\n/** PineScript `plotshape()` \u2014 a marker on each bar where the condition holds. */\nexport function plotshape(condition: Series, title?: string, options: PlotShapeOptions = {}): void {\n emitMarkers('shape', condition, title, options);\n}\n\n/** PineScript `plotchar()` \u2014 a character marker on each bar where the condition holds. */\nexport function plotchar(condition: Series, title?: string, options: PlotCharOptions = {}): void {\n emitMarkers('char', condition, title, options);\n}\n\nexport interface PlotArrowOptions {\n /** Color of the up arrows: a color or a per-bar array (default #00FF00, PineScript). */\n colorup?: string | Array<string | undefined>;\n /** Color of the down arrows: a color or a per-bar array (default #FF0000, PineScript). */\n colordown?: string | Array<string | undefined>;\n /** Display offset in bars (arrow shown at bar i + offset). */\n offset?: number;\n /** Minimal arrow height in pixels (default 5). */\n minheight?: number;\n /** Maximal arrow height in pixels (default 100). */\n maxheight?: number;\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}\n\n/**\n * PineScript `plotarrow()` \u2014 an up arrow below the bar for a positive value, a down arrow above the bar for a\n * negative value, nothing for 0 / na. The arrows go to `result.arrows` (value and color per bar), the declaration to\n * `arrowConfig`; the renderer scales the height with the absolute value between minheight and maxheight.\n */\nexport function plotarrow(series: Series, title?: string, options: PlotArrowOptions = {}): void {\n const c = collector();\n const id = `arrow${c.arrowConfig.length}`;\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 });\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 }\n): void {\n const c = collector();\n const id = `${kind}${c.barColorConfig.filter((x) => x.kind === kind).length}`;\n c.barColorConfig.push({ id, kind, title: options.title, offset: options.offset, forceOverlay: options.force_overlay });\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, forceOverlay } : { time: b[j]!.time, color: col });\n }\n}\n\n/**\n * PineScript `bgcolor()` \u2014 per-bar background color. `force_overlay: true` colors the main chart pane even when the\n * script is not an overlay.\n */\nexport function bgcolor(\n colors: string | Array<string | undefined>,\n options: { offset?: number; title?: string; force_overlay?: boolean } = {}\n): void {\n emitBarColors('bgcolor', colors, options);\n}\n\n/** PineScript `barcolor()` \u2014 per-bar candle color override. */\nexport function barcolor(\n colors: string | Array<string | undefined>,\n options: { title?: string } = {}\n): void {\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: a colour or a per-bar array (color.when); an na entry gives a transparent body */\n color?: ScriptCandleColor;\n /** Wick colour: a colour or a per-bar array */\n wickcolor?: ScriptCandleColor;\n /** Border colour: a colour or a per-bar array */\n bordercolor?: ScriptCandleColor;\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}\n\nexport interface PlotBarOptions {\n /** Bar colour: a colour or a per-bar array (color.when); an na entry gives a transparent bar */\n color?: ScriptCandleColor;\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}\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 * PineScript `plotcandle(open, high, low, close, title?, { color, wickcolor, bordercolor, display, force_overlay })`:\n * candles in `result.plotCandles[id]`, the declaration in `candleConfig`. A bar with an na value has no candle.\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 const c = collector();\n const id = `plotcandle${c.candleConfig.filter((x) => x.kind === 'candle').length}`;\n c.candleConfig.push({\n id,\n kind: 'candle',\n title,\n color: staticColor(options.color),\n wickColor: staticColor(options.wickcolor),\n borderColor: staticColor(options.bordercolor),\n display: options.display,\n forceOverlay: options.force_overlay,\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 color = candleColor(options.color, i);\n const wickColor = candleColor(options.wickcolor, i);\n const borderColor = candleColor(options.bordercolor, i);\n if (color !== undefined) candle.color = color;\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 * PineScript `plotbar(open, high, low, close, title?, { color, display, force_overlay })`: OHLC bars in\n * `result.plotBars[id]`, the declaration in `candleConfig`. A bar with an na value is not drawn.\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 const c = collector();\n const id = `plotbar${c.candleConfig.filter((x) => x.kind === 'bar').length}`;\n c.candleConfig.push({\n id,\n kind: 'bar',\n title,\n color: staticColor(options.color),\n display: options.display,\n forceOverlay: options.force_overlay,\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(options.color, 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\nexport function eachBar(fn: (c: BarContext) => number | boolean | void): Series {\n collector(); // same lifecycle guard (and error message) as the declaration calls\n const b = bars();\n const out: number[] = new Array(b.length).fill(NaN);\n const cache = new Map<Series, number[]>();\n const buffers = new Map<Series, HistoryBuffer>();\n let pendingError: { bar: number; barsBack: number } | null = null;\n let idx = 0;\n const ctx: BarContext = {\n get i() {\n return idx;\n },\n n: b.length,\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(src);\n if (!buffer) buffers.set(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 try {\n for (idx = 0; idx < b.length; idx++) {\n if (pendingError && pendingError.bar === idx) throw new Error(historyError(idx, pendingError.barsBack));\n currentBar = idx;\n setDrawingBar(idx, idx === b.length - 1, b.length - 1);\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 }\n } finally {\n currentBar = -1;\n setDrawingBar(null);\n }\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 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 return eachBar((c) => {\n engine.processBar(c.i);\n run.inLoop = true;\n try {\n return fn(c);\n } finally {\n run.inLoop = false;\n engine.processClose(c.i);\n }\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 = Object.defineProperties(\n Object.assign((title: string, options?: StrategyOptions) => declareStrategy(title, options), strategyMembers),\n variableGetters\n) as StrategyApi;\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 basecurrency?: string;\n /** Root of the symbol (PineScript `syminfo.root`): \"BTC\" for CME:BTC1!, \"ES\" for CME_MINI:ES1!, \"AAPL\" for NASDAQ:AAPL (#180) */\n root?: string;\n /** Description of the symbol (PineScript `syminfo.description`): \"Apple Inc.\" for NASDAQ:AAPL, \"Bitcoin / U.S. dollar\" for BITSTAMP:BTCUSD (#184) */\n description?: string;\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 /** 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\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>;\n\n/** A request of `request.security` for another symbol whose bars the host has not given. */\nexport interface SymbolDataRequest {\n symbol: string;\n timeframe: string;\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 super(\n `request.security needs the bars of ${requests.map((r) => `${r.symbol} (${r.timeframe})`).join(', ')}: ` +\n 'pass them with ChartContext.bars.'\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 = {\n ...timeframeCore,\n get period(): string {\n return chartTimeframe().period;\n },\n get main_period(): string {\n return 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. */\nfunction chartText(\n key: 'symbolType' | 'currency' | 'basecurrency' | 'root' | 'description' | 'foregroundColor' | 'backgroundColor',\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 return value;\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.timezone`, `syminfo.tickerid`, `syminfo.session` (session type), `syminfo.mintick`,\n * `syminfo.minmove`, `syminfo.pricescale`, `syminfo.pointvalue`, `syminfo.mincontract`, `syminfo.type`,\n * `syminfo.currency`, `syminfo.basecurrency`, `syminfo.root` and `syminfo.description`, from the chart context.\n */\nexport const syminfo = {\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 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 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 return chartText('root', 'syminfo.root');\n },\n get description(): string {\n return chartText('description', 'syminfo.description');\n },\n};\n\n/** A calendar function: `(time, timezone?)` on a UNIX time or on a Series of times. */\ninterface CalendarFunction {\n (time: number, timezone?: string): number;\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/** PineScript `year(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const year = calendar(timeCore.year);\n/** PineScript `month(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const month = calendar(timeCore.month);\n/** PineScript `weekofyear(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const weekofyear = calendar(timeCore.weekofyear);\n/** PineScript `dayofmonth(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const dayofmonth = calendar(timeCore.dayofmonth);\n/** PineScript `dayofweek(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const dayofweek = calendar(timeCore.dayofweek);\n/** PineScript `hour(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const hour = calendar(timeCore.hour);\n/** PineScript `minute(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const minute = calendar(timeCore.minute);\n/** PineScript `second(time, timezone?)`; the default time zone is the exchange time zone. */\nexport const second = calendar(timeCore.second);\n\n/**\n * PineScript `timestamp`: date string (GMT+0 by default), `(timezone, year, month, day, ...)`, or\n * `(year, month, day, ...)` in the exchange time zone.\n */\nexport function timestamp(dateString: string): number;\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;\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/** Session test of PineScript `time(timeframe, session, timezone)`; the default time zone is the exchange time zone. */\nexport function inSession(time: number, session: string, timezone?: string): boolean {\n return timeCore.inSession(time, session, timezone ?? exchangeTimezone());\n}\n\n/** PineScript `str.*`; `format_time` and the dates of `format` use the exchange time zone by default. */\nexport const 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 format_time(time: number, format: string = \"yyyy-MM-dd'T'HH:mm:ssZ\", timezone?: string): string {\n return strCore.format_time(time, format, timezone ?? exchangeTimezone());\n },\n format(pattern: string, ...args: unknown[]): string {\n return formatMessage(pattern, args, exchangeTimezone);\n },\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\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\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/**\n * PineScript `time`: the bar open time in ms (a Series), and `time(timeframe?, session?, timezone?)`:\n * the open time of the `timeframe` period that contains the bar, `na` outside `session`.\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, () => runNow);\n\nexport const time = callableSeries(new Series(ctxBars, (b) => barTime(b)), timeFunction);\n\n/**\n * PineScript `time_close`: the bar close time in ms (a Series), and `time_close(timeframe?, session?, timezone?)`.\n * Needs the chart timeframe and session.\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\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 = {\n get isfirst(): Series { return barFlag((i) => i === 0); },\n get islast(): Series { return barFlag((i, n) => i === n - 1); },\n get isconfirmed(): Series { return barFlag((i, n) => i < n - 1 || chartCtx.lastBarConfirmed === true); },\n get isrealtime(): Series { return barFlag(lastRealtime); },\n get ishistory(): Series { return barFlag((i, n) => !lastRealtime(i, n)); },\n get isnew(): Series { return barFlag((i, n) => !lastRealtime(i, n) || chartCtx.lastBarNew !== false); },\n get islastconfirmedhistory(): Series {\n return barFlag((i, n) => {\n const lastConfirmed = chartCtx.lastBarConfirmed === true && chartCtx.realtime !== true;\n return i === (lastConfirmed ? n - 1 : n - 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 = {\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 = {\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 = {\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 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 if (timeframeCore.in_seconds(tf) < timeframeCore.in_seconds(chart.period)) {\n // a lower timeframe of the chart symbol: its bars come from ChartContext.bars (#181)\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.calendar.locate(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 };\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\n chartCtx = {\n ...chartCtx,\n tickerid: symbol,\n timeframe: tf,\n timezone: info.timezone,\n session: info.session,\n regularSession: info.regularSession,\n mintick: info.mintick,\n minmove: info.minmove,\n pricescale: info.pricescale,\n pointvalue: info.pointvalue,\n mincontract: info.mincontract,\n symbolType: info.symbolType,\n currency: info.currency,\n basecurrency: info.basecurrency,\n root: info.root,\n description: info.description,\n };\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 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/** PineScript `request.*`: `security` (issue #101, other symbols #179, lower timeframes #181) and `security_lower_tf`. */\nexport const request = { security, security_lower_tf };\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. */\nexport const line = {\n ...lineCore,\n get all() {\n return lineCore.all();\n },\n};\n\n/** PineScript `label.*`; `label.all` lists the live labels in creation order. */\nexport const label = {\n ...labelCore,\n get all() {\n return labelCore.all();\n },\n};\n\n/** PineScript `box.*`; `box.all` lists the live boxes in creation order. */\nexport const box = {\n ...boxCore,\n get all() {\n return boxCore.all();\n },\n};\n\n/** PineScript `linefill.*`; `linefill.all` lists the live linefills in creation order. */\nexport const linefill = {\n ...linefillCore,\n get all() {\n return linefillCore.all();\n },\n};\n\n/** PineScript `polyline.*`; `polyline.all` lists the live polylines in creation order. */\nexport const polyline = {\n ...polylineCore,\n get all() {\n return polylineCore.all();\n },\n};\n\n/**\n * PineScript `table.*`; `table.all` lists the live tables in creation order. The live tables go to `result.tables`.\n */\nexport const table = {\n ...tableCore,\n get all() {\n return tableCore.all();\n },\n};\n\n/** PineScript `position.*` constants (table positions). */\nexport { position };\n\n/** PineScript `text.format_*`, `text.align_*` and `text.wrap_*` constants. */\nexport const text = { ...textCore };\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 = {\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 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/** Wraps a plain value array (e.g. a side output accumulated inside eachBar)\n * into a Series aligned with the current bars. */\nexport function seriesOf(values: number[]): Series {\n collector();\n return Series.fromArray(ctxBars, values);\n}\n\n/** PineScript `alertcondition()` \u2014 collected for the host's alert engine. */\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\n/** PineScript `alert()` with the `alert.freq_*` constants: `alert('Crossed', alert.freq_once_per_bar_close)`. */\nexport const alert = 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// \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, isNA as na, nz };\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\n/** PineScript `math.*`; `math.round_to_mintick(x)` uses `syminfo.mintick` of the chart context. */\nexport const math = {\n ...mathCore,\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};\nexport * as compare from '../compare/index.js';\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 M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SAAS,UAAU,SAAqD,OAAuB,gBAAsB;AACnH,QAAM,IAAI,UAAU;AACpB,MAAI,CAAC,kBAAkB,SAAS,IAAI,GAAG;AACrC,UAAM,IAAI,MAAM,uGAAuG,OAAO,IAAI,CAAC,GAAG;AAAA,EACxI;AACA,IAAE,mBAAmB;AACrB,QAAM,IAAI,QAAQ;AAClB,QAAM,SAAS,CAAC,MAAmC,OAAO,YAAY,WAAW,UAAU,QAAQ,CAAC;AACpG,QAAM,OAAO,CAAC,MAAoB;AAChC,UAAMK,QAAO,OAAO,CAAC;AACrB,QAAIA,UAAS,UAAaA,UAAS,KAAM;AACzC,MAAE,WAAW,KAAK,EAAE,MAAM,EAAE,CAAC,EAAG,MAAgB,SAAS,OAAOA,KAAI,GAAG,KAAK,CAAC;AAAA,EAC/E;AACA,MAAI,cAAc,EAAG,MAAK,UAAU;AAAA,MAC/B,UAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,IAAK,MAAK,CAAC;AAChD;AAGO,MAAM,QAAQ,OAAO,OAAO,WAAW;AAAA,EAC5C,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB,yBAAyB;AAC3B,CAAU;AA4BH,MAAM,OAAO;AAAA,EAClB,GAAG;AAAA,EACH,mBAAmB,CAAC,QAAyB,YAAqB;AAChE,UAAM,OAAO,WAAW,QAAQ;AAChC,WAAO,kBAAkB,uBAAS,SAAS,iBAAiB,QAAQ,IAAI,IAAI,SAAS,iBAAiB,QAAQ,IAAI;AAAA,EACpH;AACF;",
|
|
6
6
|
"names": ["import_registry", "import_strategy", "chart", "fixnanValues", "perBar", "staticColor", "color", "time", "open", "high", "low", "close", "ctx", "m", "d", "h", "mi", "s", "session", "bars", "timeframe", "calendar", "given", "ticker", "text"]
|
|
7
7
|
}
|