oakscriptjs 0.15.2 → 0.15.4
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/check/format.d.ts.map +1 -1
- package/dist/cjs/check/format.js +5 -0
- package/dist/cjs/check/format.js.map +2 -2
- package/dist/cjs/check/harness.d.ts +24 -0
- package/dist/cjs/check/harness.d.ts.map +1 -1
- package/dist/cjs/check/harness.js +33 -0
- package/dist/cjs/check/harness.js.map +2 -2
- package/dist/cjs/check/index.d.ts +9 -0
- package/dist/cjs/check/index.d.ts.map +1 -1
- package/dist/cjs/check/index.js +7 -0
- package/dist/cjs/check/index.js.map +2 -2
- package/dist/cjs/color/index.d.ts.map +1 -1
- package/dist/cjs/color/index.js +19 -2
- package/dist/cjs/color/index.js.map +2 -2
- package/dist/cjs/color/parse.d.ts +8 -6
- package/dist/cjs/color/parse.d.ts.map +1 -1
- package/dist/cjs/color/parse.js +15 -2
- package/dist/cjs/color/parse.js.map +2 -2
- package/dist/cjs/drawing/registry.d.ts +32 -0
- package/dist/cjs/drawing/registry.d.ts.map +1 -1
- package/dist/cjs/drawing/registry.js +179 -45
- package/dist/cjs/drawing/registry.js.map +2 -2
- package/dist/cjs/index.d.ts +2 -1
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +3 -1
- package/dist/cjs/index.js.map +2 -2
- package/dist/cjs/runtime/series.d.ts +16 -0
- package/dist/cjs/runtime/series.d.ts.map +1 -1
- package/dist/cjs/runtime/series.js +19 -2
- package/dist/cjs/runtime/series.js.map +2 -2
- package/dist/cjs/script/closure-writes.d.ts +16 -0
- package/dist/cjs/script/closure-writes.d.ts.map +1 -0
- package/dist/cjs/script/closure-writes.js +435 -0
- package/dist/cjs/script/closure-writes.js.map +7 -0
- package/dist/cjs/script/globals.d.ts +2 -0
- package/dist/cjs/script/globals.d.ts.map +1 -1
- package/dist/cjs/script/globals.js.map +1 -1
- package/dist/cjs/script/incremental.d.ts +140 -0
- package/dist/cjs/script/incremental.d.ts.map +1 -0
- package/dist/cjs/script/incremental.js +142 -0
- package/dist/cjs/script/incremental.js.map +7 -0
- package/dist/cjs/script/index.d.ts +116 -31
- package/dist/cjs/script/index.d.ts.map +1 -1
- package/dist/cjs/script/index.js +471 -25
- package/dist/cjs/script/index.js.map +3 -3
- package/dist/cjs/session/bars.d.ts +3 -0
- package/dist/cjs/session/bars.d.ts.map +1 -1
- package/dist/cjs/session/bars.js +10 -3
- package/dist/cjs/session/bars.js.map +2 -2
- package/dist/cjs/session/calendar.d.ts +19 -6
- package/dist/cjs/session/calendar.d.ts.map +1 -1
- package/dist/cjs/session/calendar.js +57 -18
- package/dist/cjs/session/calendar.js.map +2 -2
- package/dist/cjs/session/context.d.ts.map +1 -1
- package/dist/cjs/session/context.js +25 -8
- package/dist/cjs/session/context.js.map +2 -2
- package/dist/cjs/str/numberformat.d.ts.map +1 -1
- package/dist/cjs/str/numberformat.js +23 -0
- package/dist/cjs/str/numberformat.js.map +2 -2
- package/dist/cjs/strategy/index.d.ts +8 -0
- package/dist/cjs/strategy/index.d.ts.map +1 -1
- package/dist/cjs/strategy/index.js.map +1 -1
- package/dist/cjs/ta/running-sum.d.ts.map +1 -1
- package/dist/cjs/ta/running-sum.js +72 -3
- package/dist/cjs/ta/running-sum.js.map +2 -2
- package/dist/cjs/ta/step.d.ts +476 -0
- package/dist/cjs/ta/step.d.ts.map +1 -0
- package/dist/cjs/ta/step.js +1000 -0
- package/dist/cjs/ta/step.js.map +7 -0
- package/dist/cjs/ta-series.d.ts +1 -1
- package/dist/cjs/ta-series.js +3 -3
- package/dist/cjs/ta-series.js.map +1 -1
- package/dist/cjs/time/timezone.d.ts +13 -1
- package/dist/cjs/time/timezone.d.ts.map +1 -1
- package/dist/cjs/time/timezone.js +52 -13
- package/dist/cjs/time/timezone.js.map +2 -2
- package/dist/esm/check/format.d.ts.map +1 -1
- package/dist/esm/check/format.js +5 -0
- package/dist/esm/check/format.js.map +1 -1
- package/dist/esm/check/harness.d.ts +24 -0
- package/dist/esm/check/harness.d.ts.map +1 -1
- package/dist/esm/check/harness.js +40 -6
- package/dist/esm/check/harness.js.map +1 -1
- package/dist/esm/check/index.d.ts +9 -0
- package/dist/esm/check/index.d.ts.map +1 -1
- package/dist/esm/check/index.js +11 -1
- package/dist/esm/check/index.js.map +1 -1
- package/dist/esm/color/index.d.ts.map +1 -1
- package/dist/esm/color/index.js +23 -3
- package/dist/esm/color/index.js.map +1 -1
- package/dist/esm/color/parse.d.ts +8 -6
- package/dist/esm/color/parse.d.ts.map +1 -1
- package/dist/esm/color/parse.js +19 -2
- package/dist/esm/color/parse.js.map +1 -1
- package/dist/esm/drawing/registry.d.ts +32 -0
- package/dist/esm/drawing/registry.d.ts.map +1 -1
- package/dist/esm/drawing/registry.js +214 -51
- package/dist/esm/drawing/registry.js.map +1 -1
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +3 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/runtime/series.d.ts +16 -0
- package/dist/esm/runtime/series.d.ts.map +1 -1
- package/dist/esm/runtime/series.js +21 -1
- package/dist/esm/runtime/series.js.map +1 -1
- package/dist/esm/script/closure-writes.d.ts +16 -0
- package/dist/esm/script/closure-writes.d.ts.map +1 -0
- package/dist/esm/script/closure-writes.js +323 -0
- package/dist/esm/script/closure-writes.js.map +1 -0
- package/dist/esm/script/globals.d.ts +2 -0
- package/dist/esm/script/globals.d.ts.map +1 -1
- package/dist/esm/script/globals.js.map +1 -1
- package/dist/esm/script/incremental.d.ts +140 -0
- package/dist/esm/script/incremental.d.ts.map +1 -0
- package/dist/esm/script/incremental.js +173 -0
- package/dist/esm/script/incremental.js.map +1 -0
- package/dist/esm/script/index.d.ts +116 -31
- package/dist/esm/script/index.d.ts.map +1 -1
- package/dist/esm/script/index.js +561 -24
- package/dist/esm/script/index.js.map +1 -1
- package/dist/esm/session/bars.d.ts +3 -0
- package/dist/esm/session/bars.d.ts.map +1 -1
- package/dist/esm/session/bars.js +11 -3
- package/dist/esm/session/bars.js.map +1 -1
- package/dist/esm/session/calendar.d.ts +19 -6
- package/dist/esm/session/calendar.d.ts.map +1 -1
- package/dist/esm/session/calendar.js +74 -21
- package/dist/esm/session/calendar.js.map +1 -1
- package/dist/esm/session/context.d.ts.map +1 -1
- package/dist/esm/session/context.js +34 -9
- package/dist/esm/session/context.js.map +1 -1
- package/dist/esm/str/numberformat.d.ts.map +1 -1
- package/dist/esm/str/numberformat.js +30 -0
- package/dist/esm/str/numberformat.js.map +1 -1
- package/dist/esm/strategy/index.d.ts +8 -0
- package/dist/esm/strategy/index.d.ts.map +1 -1
- package/dist/esm/ta/running-sum.d.ts.map +1 -1
- package/dist/esm/ta/running-sum.js +79 -4
- package/dist/esm/ta/running-sum.js.map +1 -1
- package/dist/esm/ta/step.d.ts +476 -0
- package/dist/esm/ta/step.d.ts.map +1 -0
- package/dist/esm/ta/step.js +1089 -0
- package/dist/esm/ta/step.js.map +1 -0
- package/dist/esm/ta-series.d.ts +1 -1
- package/dist/esm/ta-series.js +4 -4
- package/dist/esm/time/timezone.d.ts +13 -1
- package/dist/esm/time/timezone.d.ts.map +1 -1
- package/dist/esm/time/timezone.js +78 -17
- package/dist/esm/time/timezone.js.map +1 -1
- package/package.json +1 -1
- package/skills/oakscript/SKILL.md +2 -2
- package/skills/oakscript/reference/check.md +5 -0
- package/skills/oakscript/reference/errors.md +0 -1
- package/skills/oakscript/reference/pine-differences.md +1 -2
- package/skills/oakscript/reference/plotting.md +5 -7
- package/skills/oakscript/reference/script-structure.md +6 -0
- package/src/check/format.ts +7 -0
- package/src/check/harness.ts +57 -0
- package/src/check/index.ts +16 -0
- package/src/color/index.ts +22 -3
- package/src/color/parse.ts +28 -3
- package/src/drawing/registry.ts +233 -50
- package/src/index.ts +4 -1
- package/src/runtime/series.ts +33 -1
- package/src/script/closure-writes.ts +279 -0
- package/src/script/globals.ts +2 -0
- package/src/script/incremental.ts +246 -0
- package/src/script/index.ts +695 -26
- package/src/session/bars.ts +11 -3
- package/src/session/calendar.ts +84 -21
- package/src/session/context.ts +36 -9
- package/src/str/numberformat.ts +29 -0
- package/src/strategy/index.ts +8 -0
- package/src/ta/running-sum.ts +78 -3
- package/src/ta/step.ts +1145 -0
- package/src/ta-series.ts +4 -4
- package/src/time/timezone.ts +76 -15
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/session/context.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The session of a chart context, for code that does not run a whole script (a port with its own bar loop).\n *\n * The same values as the script API gives (`time(tf)`, `time_close(tf)`, `time_tradingday`, `session.*`, the periods\n * of `request.security`), from the session, corrections and holidays of the context. Bar times are in the unit of\n * the context (`timeUnit`, seconds by default, as `Bar.time`); PineScript time values are returned in ms.\n *\n * @module session/context\n */\n\nimport type { Bar } from '../types/index.js';\nimport { info, in_seconds } from '../timeframe/index.js';\nimport { afterCompletion, periodsOf, resample } from '../security/resample.js';\nimport { parsePineSession, sessionRun } from '../time/session.js';\nimport { SessionBars, sessionFlags, strayPeriods, type SessionFlags } from './bars.js';\nimport { TradingCalendar, type SessionSpec } from './calendar.js';\n\n/** The part of a chart context that the session functions read (a `ChartContext` of the script API fits). */\nexport interface SessionContext {\n /** Chart timeframe: \"5\", \"60\", \"1D\"... */\n timeframe?: string;\n /** Exchange time zone: \"America/New_York\", \"Etc/UTC\"... */\n timezone?: string;\n /** Session of the loaded bars: hours, corrections, holidays */\n session?: SessionSpec | string;\n /** Regular trading hours when the bars include extended hours (default: `session`) */\n regularSession?: SessionSpec | string;\n /** Unit of the bar times: 's' (default) or 'ms' */\n timeUnit?: 's' | 'ms';\n}\n\n/** The session calendars of a context: the loaded bars and the regular hours. */\nexport interface ChartSessions {\n bars: SessionBars;\n regular: SessionBars;\n /** ms per unit of the bar times */\n unit: number;\n}\n\nconst toSpec = (s: SessionSpec | string): SessionSpec => (typeof s === 'string' ? { session: s } : s);\nconst cache = new WeakMap<object, ChartSessions>();\n\n/**\n * Session calendars of a chart context (cached per context object).\n * @throws Error when the context has no timeframe, time zone or session\n */\nexport function chartSessions(chart: SessionContext): ChartSessions {\n const cached = cache.get(chart);\n if (cached) return cached;\n const { timeframe, timezone, session } = chart;\n if (!timeframe || !timezone || !session) {\n throw new Error('The chart context needs timeframe, timezone and session for the session functions.');\n }\n const loaded = toSpec(session);\n const regular = chart.regularSession ? toSpec(chart.regularSession) : loaded;\n const out: ChartSessions = {\n bars: new SessionBars(new TradingCalendar(timezone, loaded), timeframe),\n regular: new SessionBars(new TradingCalendar(timezone, { holidays: loaded.holidays, ...regular }), timeframe),\n unit: chart.timeUnit === 'ms' ? 1 : 1000,\n };\n cache.set(chart, out);\n return out;\n}\n\n/** Open and close (ms) of the period that contains a bar opening at a time in ms; NaN outside the session. */\nexport interface SessionPeriods {\n open: (time: number) => number;\n close: (time: number) => number;\n}\n\n/**\n * Calendar for the `session` / `timezone` arguments of `time(tf, session, timezone)`. Without both: the loaded\n * session. As in PineScript, an explicit time zone reads the symbol session hours in that zone without corrections\n * and holidays, and an explicit session follows PineScript's session string rules.\n */\nfunction calendarFor(\n bars: SessionBars,\n chart: SessionContext,\n session: string | undefined,\n timezone: string | undefined,\n dayPlacement: boolean\n): { bars: SessionBars; test: boolean; inside?: (time: number) => boolean } {\n if (!session && !timezone) return { bars, test: false };\n const tz = timezone ?? chart.timezone!;\n // a session string that is empty or does not start with a digit is the symbol session: \"regular\" the regular\n // hours, \"extended\" and any other name the loaded hours (PineScript)\n if (session !== undefined && parsePineSession(session) === null) {\n const name = session.trim();\n const symbol = name === 'regular' && chart.regularSession ? chart.regularSession : chart.session!;\n return { bars: new SessionBars(new TradingCalendar(tz, { session: toSpec(symbol).session }, 'symbol'), bars.chart.period), test: true };\n }\n const spec = session ? { session } : { session: toSpec(chart.session!).session };\n return {\n bars: new SessionBars(new TradingCalendar(tz, spec, session ? 'pine' : 'symbol', dayPlacement), bars.chart.period),\n test: true,\n // a PineScript session string: the rules of time.inSession (runs ending at 0000, days around a clock change)\n inside: session ? (time) => sessionRun(time, session, tz, in_seconds(bars.chart.period) * 1000) !== null : undefined,\n };\n}\n\n/**\n * `time(tf, session, timezone)` / `time_close(tf, session, timezone)` of a bar, as PineScript computes them (#173):\n * an intraday timeframe tests the bar with the session rules of time.inSession and aligns its periods on the start\n * of the run that contains the bar; \"D\" tests the bar against the day's session period (the calendar; the time\n * between two runs of a day is inside it, #182); a timeframe of more than one day (\"2D\", \"W\", \"M\") has no test and\n * keeps the period's time. `bars` is the calendar of the loaded session (`chartSessions(chart).bars`).\n */\nexport function sessionPeriods(\n bars: SessionBars,\n chart: SessionContext,\n timeframe: string,\n session?: string,\n timezone?: string\n): SessionPeriods {\n const tf = info(timeframe);\n const { bars: calendar, test, inside } = calendarFor(bars, chart, session, timezone, !tf.isintraday);\n const open = (t: number): number => calendar.timeOf(t, timeframe);\n const close = (t: number): number => calendar.closeOf(t, timeframe);\n if (!test) return { open, close };\n if (tf.isintraday) {\n if (session !== undefined && parsePineSession(session) !== null && !calendar.chart.isdwm) {\n const tz = timezone ?? chart.timezone!;\n const barMs = in_seconds(calendar.chart.period) * 1000;\n const ms = in_seconds(tf.period) * 1000;\n const run = (t: number) => sessionRun(t, session, tz, barMs);\n const start = (t: number, r: [number, number]) => r[0] + Math.floor((t - r[0]) / ms) * ms;\n return {\n open: (t) => { const r = run(t); return r ? start(t, r) : NaN; },\n close: (t) => { const r = run(t); return r ? Math.min(start(t, r) + ms, r[1]) : NaN; },\n };\n }\n const isIn = (t: number) => (inside ? inside(t) : calendar.inside(t));\n return { open: (t) => (isIn(t) ? open(t) : NaN), close: (t) => (isIn(t) ? close(t) : NaN) };\n }\n if (tf.isdaily && tf.multiplier === 1) {\n return { open: (t) => (calendar.inside(t) ? open(t) : NaN), close: (t) => (calendar.inside(t) ? close(t) : NaN) };\n }\n return { open, close };\n}\n\nconst periodCache = new WeakMap<object, Map<string, SessionPeriods>>();\n\nfunction periodsOfChart(chart: SessionContext, timeframe: string, session?: string, timezone?: string): { s: ChartSessions; p: SessionPeriods } {\n const s = chartSessions(chart);\n let byKey = periodCache.get(chart);\n if (!byKey) periodCache.set(chart, (byKey = new Map()));\n const key = `${timeframe}|${session ?? ''}|${timezone ?? ''}`;\n let p = byKey.get(key);\n if (!p) byKey.set(key, (p = sessionPeriods(s.bars, chart, timeframe, session, timezone)));\n return { s, p };\n}\n\n/**\n * PineScript `time(timeframe, session, timezone)` (ms) of a bar that opens at `time`: the start of its period; NaN\n * without one or outside `session` (#182). Without `session` and `timezone`, the periods of the loaded session.\n */\nexport function periodTime(time: number, timeframe: string, chart: SessionContext, session?: string, timezone?: string): number {\n const { s, p } = periodsOfChart(chart, timeframe, session, timezone);\n return p.open(time * s.unit);\n}\n\n/** PineScript `time_close(timeframe, session, timezone)` (ms) of a bar that opens at `time` (#182). */\nexport function periodClose(time: number, timeframe: string, chart: SessionContext, session?: string, timezone?: string): number {\n const { s, p } = periodsOfChart(chart, timeframe, session, timezone);\n return p.close(time * s.unit);\n}\n\n/** PineScript `time_tradingday` (ms, 00:00 UTC of the trading day) of a bar that opens at `time`. */\nexport function tradingDayTime(time: number, chart: SessionContext): number {\n const s = chartSessions(chart);\n return s.bars.tradingDayTime(time * s.unit);\n}\n\n/** PineScript `session.*` flags of bars that open at `times` (in order). */\nexport function chartSessionFlags(times: ArrayLike<number>, chart: SessionContext): SessionFlags {\n const s = chartSessions(chart);\n return sessionFlags(Array.from(times, (t) => t * s.unit), s.bars, s.regular);\n}\n\n/** Higher-timeframe bars of the chart bars and what `mapToChart` needs to bring values back to the chart. */\nexport interface SessionResample {\n /** Bars of `timeframe`, built from the chart bars */\n bars: Bar[];\n /** Period index of each chart bar */\n group: number[];\n /** Latest completed period at each chart bar */\n latest: number[];\n}\n\n/**\n * Same-symbol `request.security` on a timeframe equal to or higher than the chart's, with the session of the context:\n * D / W / M periods follow the regular hours, corrections and holidays; intraday periods the loaded session.\n * Compute on `bars`, then bring each value series back with `mapToChart(values, group, latest, lookahead, gaps)`.\n * @throws Error when `timeframe` is lower than the chart timeframe\n */\nexport function resampleSession(bars: Bar[], timeframe: string, chart: SessionContext): SessionResample {\n const s = chartSessions(chart);\n const chartTf = s.bars.chart;\n const tf = info(timeframe || chartTf.period);\n if (tf.period === chartTf.period) {\n const group = bars.map((_, i) => i);\n return { bars, group, latest: group };\n }\n if (in_seconds(tf.period) < in_seconds(chartTf.period)) {\n throw new Error(`resampleSession: timeframe \"${tf.period}\" is lower than the chart timeframe \"${chartTf.period}\".`);\n }\n const times = bars.map((b) => (b.time as number) * s.unit);\n const calendar = tf.isdwm ? s.regular : s.bars;\n const starts = times.map((t) => calendar.timeOf(t, tf.period));\n const dayPeriods = times.map((t, i) => {\n const at = s.bars.calendar.locate(t);\n const periods = at ? calendar.calendar.periods(at.date) : [];\n return periods.length ? calendar.timeOf(periods[0]![0], tf.period) : starts[i]!;\n });\n strayPeriods(starts, dayPeriods, times, s.bars, tf.isdwm ? null : in_seconds(tf.period) * 1000);\n const reaches = times.map((t) => s.bars.closeOf(t, chartTf.period) >= calendar.periodEnd(t, tf.period));\n const { group, latest } = periodsOf(starts, dayPeriods, reaches);\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 return { bars: resample(bars.filter(kept), starts.map((x) => x / s.unit).filter(kept)).bars, group, latest };\n}\n\n/**\n * Open time of the `count`-th bar after the bar that opens at `time`, on the trading calendar of the context: the\n * closed hours, weekends, holidays and days off are skipped. `count` 0 is the bar itself. For a drawing that ends\n * `count` bars after the last bar (PineScript `bar_index + count`).\n */\nexport function barTimeAfter(time: number, count: number, chart: SessionContext): number {\n const s = chartSessions(chart);\n let t = time * s.unit;\n for (let k = 0; k < count && !Number.isNaN(t); k++) t = s.bars.nextBarTime(t);\n return t / s.unit;\n}\n\n/**\n * Number of bars from the bar that opens at `from` to the bar that contains `to`, on the trading calendar of the\n * context (0 when `to` is in the bar of `from` or before it). For a drawing placed at a time after the last bar\n * (PineScript `time + n days` with `xloc.bar_time`): the chart shows it on the bar of that time, weekends and\n * holidays skipped. `to` is first rounded to the nearest second, a half second going up (#174: 15 ms before a bar\n * opens is on that bar, 501 ms before is on the bar before). NaN when no bar is found within 100,000 bars.\n */\nexport function barsUntil(from: number, to: number, chart: SessionContext): number {\n const s = chartSessions(chart);\n const target = Math.floor((to * s.unit) / 1000 + 0.5) * 1000;\n let t = from * s.unit;\n for (let k = 0; k < 100_000; k++) {\n const next = s.bars.nextBarTime(t);\n if (Number.isNaN(next)) return NaN;\n if (next > target) return k;\n t = next;\n }\n return NaN;\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,uBAAiC;AACjC,sBAAqD;AACrD,qBAA6C;AAC7C,kBAA2E;AAC3E,sBAAkD;AAwBlD,MAAM,SAAS,CAAC,MAA0C,OAAO,MAAM,WAAW,EAAE,SAAS,EAAE,IAAI;AACnG,MAAM,QAAQ,oBAAI,QAA+B;AAM1C,SAAS,cAAc,OAAsC;AAClE,QAAM,SAAS,MAAM,IAAI,KAAK;AAC9B,MAAI,OAAQ,QAAO;AACnB,QAAM,EAAE,WAAW,UAAU,QAAQ,IAAI;AACzC,MAAI,CAAC,aAAa,CAAC,YAAY,CAAC,SAAS;AACvC,UAAM,IAAI,MAAM,oFAAoF;AAAA,EACtG;AACA,QAAM,SAAS,OAAO,OAAO;AAC7B,QAAM,UAAU,MAAM,iBAAiB,OAAO,MAAM,cAAc,IAAI;AACtE,QAAM,MAAqB;AAAA,IACzB,MAAM,IAAI,wBAAY,IAAI,gCAAgB,UAAU,MAAM,GAAG,SAAS;AAAA,IACtE,SAAS,IAAI,wBAAY,IAAI,gCAAgB,UAAU,EAAE,UAAU,OAAO,UAAU,GAAG,QAAQ,CAAC,GAAG,SAAS;AAAA,IAC5G,MAAM,MAAM,aAAa,OAAO,IAAI;AAAA,EACtC;AACA,QAAM,IAAI,OAAO,GAAG;AACpB,SAAO;AACT;
|
|
4
|
+
"sourcesContent": ["/**\n * The session of a chart context, for code that does not run a whole script (a port with its own bar loop).\n *\n * The same values as the script API gives (`time(tf)`, `time_close(tf)`, `time_tradingday`, `session.*`, the periods\n * of `request.security`), from the session, corrections and holidays of the context. Bar times are in the unit of\n * the context (`timeUnit`, seconds by default, as `Bar.time`); PineScript time values are returned in ms.\n *\n * @module session/context\n */\n\nimport type { Bar } from '../types/index.js';\nimport { info, in_seconds } from '../timeframe/index.js';\nimport { afterCompletion, periodsOf, resample } from '../security/resample.js';\nimport { parsePineSession, sessionRun } from '../time/session.js';\nimport { SessionBars, sessionFlags, strayPeriods, type SessionFlags } from './bars.js';\nimport { TradingCalendar, type SessionSpec } from './calendar.js';\n\n/** The part of a chart context that the session functions read (a `ChartContext` of the script API fits). */\nexport interface SessionContext {\n /** Chart timeframe: \"5\", \"60\", \"1D\"... */\n timeframe?: string;\n /** Exchange time zone: \"America/New_York\", \"Etc/UTC\"... */\n timezone?: string;\n /** Session of the loaded bars: hours, corrections, holidays */\n session?: SessionSpec | string;\n /** Regular trading hours when the bars include extended hours (default: `session`) */\n regularSession?: SessionSpec | string;\n /** Unit of the bar times: 's' (default) or 'ms' */\n timeUnit?: 's' | 'ms';\n}\n\n/** The session calendars of a context: the loaded bars and the regular hours. */\nexport interface ChartSessions {\n bars: SessionBars;\n regular: SessionBars;\n /** ms per unit of the bar times */\n unit: number;\n}\n\nconst toSpec = (s: SessionSpec | string): SessionSpec => (typeof s === 'string' ? { session: s } : s);\nconst cache = new WeakMap<object, ChartSessions>();\n\n/**\n * Session calendars of a chart context (cached per context object).\n * @throws Error when the context has no timeframe, time zone or session\n */\nexport function chartSessions(chart: SessionContext): ChartSessions {\n const cached = cache.get(chart);\n if (cached) return cached;\n const { timeframe, timezone, session } = chart;\n if (!timeframe || !timezone || !session) {\n throw new Error('The chart context needs timeframe, timezone and session for the session functions.');\n }\n const loaded = toSpec(session);\n const regular = chart.regularSession ? toSpec(chart.regularSession) : loaded;\n const out: ChartSessions = {\n bars: new SessionBars(new TradingCalendar(timezone, loaded), timeframe),\n regular: new SessionBars(new TradingCalendar(timezone, { holidays: loaded.holidays, ...regular }), timeframe),\n unit: chart.timeUnit === 'ms' ? 1 : 1000,\n };\n cache.set(chart, out);\n return out;\n}\n\n/** Open and close (ms) of the period that contains a bar opening at a time in ms; NaN outside the session. */\nexport interface SessionPeriods {\n open: (time: number) => number;\n close: (time: number) => number;\n}\n\n/** Calendars of the `session` / `timezone` arguments before the cache restarts */\nconst MAX_ARGUMENT_CALENDARS = 64;\nconst argumentCalendars = new Map<string, TradingCalendar>();\n\n/**\n * Calendar of a session string read in a time zone, without corrections and holidays: it depends on these only, so\n * the calls with other timeframes or other chart contexts share it and its periods (a script often reads\n * `time(timeframe.period, s)` and `time(\"D\", s)` on every bar).\n */\nfunction argumentCalendar(timezone: string, session: string, rule: 'symbol' | 'pine', dayPlacement: boolean): TradingCalendar {\n const key = `${rule}|${dayPlacement}|${timezone}|${session}`;\n let calendar = argumentCalendars.get(key);\n if (!calendar) {\n calendar = new TradingCalendar(timezone, { session }, rule, dayPlacement);\n if (argumentCalendars.size >= MAX_ARGUMENT_CALENDARS) argumentCalendars.clear();\n argumentCalendars.set(key, calendar);\n }\n return calendar;\n}\n\n/**\n * Calendar for the `session` / `timezone` arguments of `time(tf, session, timezone)`. Without both: the loaded\n * session. As in PineScript, an explicit time zone reads the symbol session hours in that zone without corrections\n * and holidays, and an explicit session follows PineScript's session string rules.\n */\nfunction calendarFor(\n bars: SessionBars,\n chart: SessionContext,\n session: string | undefined,\n timezone: string | undefined,\n dayPlacement: boolean\n): { bars: SessionBars; test: boolean; inside?: (time: number) => boolean } {\n if (!session && !timezone) return { bars, test: false };\n const tz = timezone ?? chart.timezone!;\n // a session string that is empty or does not start with a digit is the symbol session: \"regular\" the regular\n // hours, \"extended\" and any other name the loaded hours (PineScript)\n if (session !== undefined && parsePineSession(session) === null) {\n const name = session.trim();\n const symbol = name === 'regular' && chart.regularSession ? chart.regularSession : chart.session!;\n return { bars: new SessionBars(argumentCalendar(tz, toSpec(symbol).session, 'symbol', false), bars.chart.period), test: true };\n }\n return {\n bars: new SessionBars(\n argumentCalendar(tz, session || toSpec(chart.session!).session, session ? 'pine' : 'symbol', dayPlacement),\n bars.chart.period\n ),\n test: true,\n // a PineScript session string: the rules of time.inSession (runs ending at 0000, days around a clock change)\n inside: session ? (time) => sessionRun(time, session, tz, in_seconds(bars.chart.period) * 1000) !== null : undefined,\n };\n}\n\n/**\n * `time(tf, session, timezone)` / `time_close(tf, session, timezone)` of a bar, as PineScript computes them (#173):\n * an intraday timeframe tests the bar with the session rules of time.inSession and aligns its periods on the start\n * of the run that contains the bar; \"D\" tests the bar against the day's session period (the calendar; the time\n * between two runs of a day is inside it, #182); a timeframe of more than one day (\"2D\", \"W\", \"M\") has no test and\n * keeps the period's time. `bars` is the calendar of the loaded session (`chartSessions(chart).bars`).\n */\nexport function sessionPeriods(\n bars: SessionBars,\n chart: SessionContext,\n timeframe: string,\n session?: string,\n timezone?: string\n): SessionPeriods {\n const tf = info(timeframe);\n const { bars: calendar, test, inside } = calendarFor(bars, chart, session, timezone, !tf.isintraday);\n const open = (t: number): number => calendar.timeOf(t, timeframe);\n const close = (t: number): number => calendar.closeOf(t, timeframe);\n if (!test) return { open, close };\n if (tf.isintraday) {\n if (session !== undefined && parsePineSession(session) !== null && !calendar.chart.isdwm) {\n const tz = timezone ?? chart.timezone!;\n const barMs = in_seconds(calendar.chart.period) * 1000;\n const ms = in_seconds(tf.period) * 1000;\n const run = (t: number) => sessionRun(t, session, tz, barMs);\n const start = (t: number, r: [number, number]) => r[0] + Math.floor((t - r[0]) / ms) * ms;\n return {\n open: (t) => { const r = run(t); return r ? start(t, r) : NaN; },\n close: (t) => { const r = run(t); return r ? Math.min(start(t, r) + ms, r[1]) : NaN; },\n };\n }\n const isIn = (t: number) => (inside ? inside(t) : calendar.inside(t));\n return { open: (t) => (isIn(t) ? open(t) : NaN), close: (t) => (isIn(t) ? close(t) : NaN) };\n }\n if (tf.isdaily && tf.multiplier === 1) {\n return { open: (t) => (calendar.inside(t) ? open(t) : NaN), close: (t) => (calendar.inside(t) ? close(t) : NaN) };\n }\n return { open, close };\n}\n\n/** Periods per chart, timeframe, session and time zone (no session / time zone is \"\"): maps of the given strings, no\n * key to build on every bar */\nconst periodCache = new WeakMap<object, Map<string, Map<string, Map<string, SessionPeriods>>>>();\n\nfunction periodsOfChart(chart: SessionContext, timeframe: string, session?: string, timezone?: string): { s: ChartSessions; p: SessionPeriods } {\n const s = chartSessions(chart);\n let byTimeframe = periodCache.get(chart);\n if (!byTimeframe) periodCache.set(chart, (byTimeframe = new Map()));\n let bySession = byTimeframe.get(timeframe);\n if (!bySession) byTimeframe.set(timeframe, (bySession = new Map()));\n let byZone = bySession.get(session ?? '');\n if (!byZone) bySession.set(session ?? '', (byZone = new Map()));\n let p = byZone.get(timezone ?? '');\n if (!p) byZone.set(timezone ?? '', (p = sessionPeriods(s.bars, chart, timeframe, session, timezone)));\n return { s, p };\n}\n\n/**\n * PineScript `time(timeframe, session, timezone)` (ms) of a bar that opens at `time`: the start of its period; NaN\n * without one or outside `session` (#182). Without `session` and `timezone`, the periods of the loaded session.\n */\nexport function periodTime(time: number, timeframe: string, chart: SessionContext, session?: string, timezone?: string): number {\n const { s, p } = periodsOfChart(chart, timeframe, session, timezone);\n return p.open(time * s.unit);\n}\n\n/** PineScript `time_close(timeframe, session, timezone)` (ms) of a bar that opens at `time` (#182). */\nexport function periodClose(time: number, timeframe: string, chart: SessionContext, session?: string, timezone?: string): number {\n const { s, p } = periodsOfChart(chart, timeframe, session, timezone);\n return p.close(time * s.unit);\n}\n\n/** PineScript `time_tradingday` (ms, 00:00 UTC of the trading day) of a bar that opens at `time`. */\nexport function tradingDayTime(time: number, chart: SessionContext): number {\n const s = chartSessions(chart);\n return s.bars.tradingDayTime(time * s.unit);\n}\n\n/** PineScript `session.*` flags of bars that open at `times` (in order). */\nexport function chartSessionFlags(times: ArrayLike<number>, chart: SessionContext): SessionFlags {\n const s = chartSessions(chart);\n return sessionFlags(Array.from(times, (t) => t * s.unit), s.bars, s.regular);\n}\n\n/** Higher-timeframe bars of the chart bars and what `mapToChart` needs to bring values back to the chart. */\nexport interface SessionResample {\n /** Bars of `timeframe`, built from the chart bars */\n bars: Bar[];\n /** Period index of each chart bar */\n group: number[];\n /** Latest completed period at each chart bar */\n latest: number[];\n}\n\n/**\n * Same-symbol `request.security` on a timeframe equal to or higher than the chart's, with the session of the context:\n * D / W / M periods follow the regular hours, corrections and holidays; intraday periods the loaded session.\n * Compute on `bars`, then bring each value series back with `mapToChart(values, group, latest, lookahead, gaps)`.\n * @throws Error when `timeframe` is lower than the chart timeframe\n */\nexport function resampleSession(bars: Bar[], timeframe: string, chart: SessionContext): SessionResample {\n const s = chartSessions(chart);\n const chartTf = s.bars.chart;\n const tf = info(timeframe || chartTf.period);\n if (tf.period === chartTf.period) {\n const group = bars.map((_, i) => i);\n return { bars, group, latest: group };\n }\n if (in_seconds(tf.period) < in_seconds(chartTf.period)) {\n throw new Error(`resampleSession: timeframe \"${tf.period}\" is lower than the chart timeframe \"${chartTf.period}\".`);\n }\n const times = bars.map((b) => (b.time as number) * s.unit);\n const calendar = tf.isdwm ? s.regular : s.bars;\n const starts = times.map((t) => calendar.timeOf(t, tf.period));\n const dayPeriods = times.map((t, i) => {\n const at = s.bars.calendar.locate(t);\n const periods = at ? calendar.calendar.periods(at.date) : [];\n return periods.length ? calendar.timeOf(periods[0]![0], tf.period) : starts[i]!;\n });\n strayPeriods(starts, dayPeriods, times, s.bars, tf.isdwm ? null : in_seconds(tf.period) * 1000);\n const reaches = times.map((t) => s.bars.closeOf(t, chartTf.period) >= calendar.periodEnd(t, tf.period));\n const { group, latest } = periodsOf(starts, dayPeriods, reaches);\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 return { bars: resample(bars.filter(kept), starts.map((x) => x / s.unit).filter(kept)).bars, group, latest };\n}\n\n/**\n * Open time of the `count`-th bar after the bar that opens at `time`, on the trading calendar of the context: the\n * closed hours, weekends, holidays and days off are skipped. `count` 0 is the bar itself. For a drawing that ends\n * `count` bars after the last bar (PineScript `bar_index + count`).\n */\nexport function barTimeAfter(time: number, count: number, chart: SessionContext): number {\n const s = chartSessions(chart);\n let t = time * s.unit;\n for (let k = 0; k < count && !Number.isNaN(t); k++) t = s.bars.nextBarTime(t);\n return t / s.unit;\n}\n\n/**\n * Number of bars from the bar that opens at `from` to the bar that contains `to`, on the trading calendar of the\n * context (0 when `to` is in the bar of `from` or before it). For a drawing placed at a time after the last bar\n * (PineScript `time + n days` with `xloc.bar_time`): the chart shows it on the bar of that time, weekends and\n * holidays skipped. `to` is first rounded to the nearest second, a half second going up (#174: 15 ms before a bar\n * opens is on that bar, 501 ms before is on the bar before). NaN when no bar is found within 100,000 bars.\n */\nexport function barsUntil(from: number, to: number, chart: SessionContext): number {\n const s = chartSessions(chart);\n const target = Math.floor((to * s.unit) / 1000 + 0.5) * 1000;\n let t = from * s.unit;\n for (let k = 0; k < 100_000; k++) {\n const next = s.bars.nextBarTime(t);\n if (Number.isNaN(next)) return NaN;\n if (next > target) return k;\n t = next;\n }\n return NaN;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,uBAAiC;AACjC,sBAAqD;AACrD,qBAA6C;AAC7C,kBAA2E;AAC3E,sBAAkD;AAwBlD,MAAM,SAAS,CAAC,MAA0C,OAAO,MAAM,WAAW,EAAE,SAAS,EAAE,IAAI;AACnG,MAAM,QAAQ,oBAAI,QAA+B;AAM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,YAAY,CAAC;AAC5E,SAAO,IAAI,EAAE;AACf;AASO,SAAS,UAAU,MAAc,IAAY,OAA+B;AACjF,QAAM,IAAI,cAAc,KAAK;AAC7B,QAAM,SAAS,KAAK,MAAO,KAAK,EAAE,OAAQ,MAAO,GAAG,IAAI;AACxD,MAAI,IAAI,OAAO,EAAE;AACjB,WAAS,IAAI,GAAG,IAAI,KAAS,KAAK;AAChC,UAAM,OAAO,EAAE,KAAK,YAAY,CAAC;AACjC,QAAI,OAAO,MAAM,IAAI,EAAG,QAAO;AAC/B,QAAI,OAAO,OAAQ,QAAO;AAC1B,QAAI;AAAA,EACN;AACA,SAAO;AACT;",
|
|
6
6
|
"names": ["group"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"numberformat.d.ts","sourceRoot":"","sources":["../../../src/str/numberformat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAIH,MAAM,MAAM,QAAQ,GAAG,gBAAgB,GAAG,aAAa,GAAG,eAAe,GAAG,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"numberformat.d.ts","sourceRoot":"","sources":["../../../src/str/numberformat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAIH,MAAM,MAAM,QAAQ,GAAG,gBAAgB,GAAG,aAAa,GAAG,eAAe,GAAG,mBAAmB,CAAC;AAkLhG,qDAAqD;AACrD,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,GAAG,MAAM,CAmBnF;AAyCD;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAMhF"}
|
|
@@ -151,7 +151,30 @@ function layout(d, p) {
|
|
|
151
151
|
if (!int && !frac) int = "0";
|
|
152
152
|
return group(int, p.grouping) + (frac ? "." + frac : "");
|
|
153
153
|
}
|
|
154
|
+
const formatted = /* @__PURE__ */ new Map();
|
|
155
|
+
let formattedCount = 0;
|
|
156
|
+
const FORMATTED_KEPT = 1e5;
|
|
154
157
|
function formatNumber(value, pattern, mode) {
|
|
158
|
+
if (Number.isNaN(value) || Object.is(value, -0)) return format(value, pattern, mode);
|
|
159
|
+
let byPattern = formatted.get(mode);
|
|
160
|
+
if (byPattern === void 0) formatted.set(mode, byPattern = /* @__PURE__ */ new Map());
|
|
161
|
+
let byValue = byPattern.get(pattern);
|
|
162
|
+
if (byValue === void 0) byPattern.set(pattern, byValue = /* @__PURE__ */ new Map());
|
|
163
|
+
let text = byValue.get(value);
|
|
164
|
+
if (text === void 0) {
|
|
165
|
+
text = format(value, pattern, mode);
|
|
166
|
+
if (formattedCount >= FORMATTED_KEPT) {
|
|
167
|
+
formatted.clear();
|
|
168
|
+
formattedCount = 0;
|
|
169
|
+
formatted.set(mode, byPattern = /* @__PURE__ */ new Map());
|
|
170
|
+
byPattern.set(pattern, byValue = /* @__PURE__ */ new Map());
|
|
171
|
+
}
|
|
172
|
+
byValue.set(value, text);
|
|
173
|
+
formattedCount++;
|
|
174
|
+
}
|
|
175
|
+
return text;
|
|
176
|
+
}
|
|
177
|
+
function format(value, pattern, mode) {
|
|
155
178
|
if (Number.isNaN(value)) return "NaN";
|
|
156
179
|
const p = parsePattern(pattern);
|
|
157
180
|
if (!Number.isFinite(value)) return affixes(p, value < 0, "\u221E");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/str/numberformat.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Number patterns (\"#.##\", \"#,##0.00\", \"0.00E0\", \"#.##%\", \"'#'#.##\") as PineScript formats them.\n *\n * The pattern syntax is Java's DecimalFormat: `0` required digit, `#` optional digit, `,` grouping,\n * `.` decimal point, `E0` exponent, `%` multiplies by 100, `'...'` quoted literal text.\n * PineScript rules:\n * - `str.tostring` with a format rounds half away from zero on the shortest decimal form of the number\n * (`1.005` with \"#.##\" gives \"1.01\", `2.5` with \"#\" gives \"3\")\n * - `str.tostring` without a format rounds the digits of the JVM's binary to decimal conversion to 10 decimals,\n * half to even, the conversion flags deciding a tie (see `floatingdecimal.ts`): 12.34500000005 gives \"12.345\"\n * (\"12.3450000001\" with the format \"#.##########\"), 1791662400001 / 900000 gives \"1990736.000001111\"\n * - `str.format` rounds half to even on the exact binary value (`0.25` with \"#.#\" gives \"0.2\")\n * - a negative number that rounds to zero loses its sign, except with \"%\" (\"#.#%\": -0.0004 gives \"-0%\");\n * \"#.00\" writes `.50` (no leading zero),\n * but \"#.##\" writes `0.5` (a pattern without any '0' shows one integer digit)\n * - with an exponent, the value is first rounded to the fraction digits (\"0.00E0\": 0.125 gives \"1.30E-1\")\n * - a pattern without digit characters (`format.price` is \"price\") formats like \"#\" after its text,\n * and keeps the sign: -0.004 gives \"-price0\"\n * - \"pos;neg\": a negative number uses the text around the digits of the negative subpattern instead of \"-\"\n * (\"#.##;(#.##)\" gives \"(3.5)\" for -3.5); the digits follow the positive subpattern, as in Java\n * - at most 16 decimals when |x| >= 1e-3 (the shortest digits of a double never have more there):\n * 0.1 with 20 '#' decimals gives \"0.1\" in both rounding modes\n */\n\nimport { javaFixedDigits, pow5, trimZeros } from './floatingdecimal.js';\n\nexport type Rounding = 'halfUpShortest' | 'halfUpExact' | 'halfEvenExact' | 'halfEvenConverted';\n\ninterface Pattern {\n prefix: string;\n suffix: string;\n /** Text around the digits of the negative subpattern (\"pos;neg\"), or null without one */\n negPrefix: string | null;\n negSuffix: string | null;\n minInt: number;\n minFrac: number;\n maxFrac: number;\n /** Digits per group, 0 without grouping */\n grouping: number;\n percent: boolean;\n /** Minimum exponent digits, or null without exponent */\n exponent: number | null;\n hasDigits: boolean;\n}\n\nconst patterns = new Map<string, Pattern>();\n\n/** Index of the first ';' outside quotes, or -1. */\nfunction subpatternSplit(pattern: string): number {\n let quoted = false;\n for (let i = 0; i < pattern.length; i++) {\n if (pattern[i] === \"'\") quoted = !quoted;\n else if (pattern[i] === ';' && !quoted) return i;\n }\n return -1;\n}\n\nfunction parsePattern(pattern: string): Pattern {\n const cached = patterns.get(pattern);\n if (cached) return cached;\n const semi = subpatternSplit(pattern);\n if (semi !== -1) {\n // only the text around the digits of the negative subpattern is used\n const neg = parsePattern(pattern.slice(semi + 1));\n const parsed = { ...parsePattern(pattern.slice(0, semi)), negPrefix: neg.prefix, negSuffix: neg.suffix };\n patterns.set(pattern, parsed);\n return parsed;\n }\n\n let prefix = '';\n let suffix = '';\n let number = '';\n let percent = false;\n let phase: 'prefix' | 'number' | 'suffix' = 'prefix';\n for (let i = 0; i < pattern.length; i++) {\n const ch = pattern[i]!;\n let literal: string;\n if (ch === \"'\") {\n const end = pattern.indexOf(\"'\", i + 1);\n if (end === i + 1) {\n literal = \"'\";\n i = end;\n } else {\n literal = pattern.slice(i + 1, end === -1 ? undefined : end);\n i = end === -1 ? pattern.length : end;\n }\n } else if (phase !== 'suffix' && ('#0,.'.includes(ch) || (phase === 'number' && ch === 'E'))) {\n phase = 'number';\n number += ch;\n continue;\n } else {\n if (ch === '%') percent = true;\n literal = ch;\n }\n if (phase === 'number') phase = 'suffix';\n if (phase === 'prefix') prefix += literal;\n else suffix += literal;\n }\n\n const [mantissa = '', exp] = number.split('E');\n const [intPart = '', fracPart = ''] = mantissa.split('.');\n const lastComma = intPart.lastIndexOf(',');\n const parsed: Pattern = {\n prefix,\n suffix,\n negPrefix: null,\n negSuffix: null,\n // as in Java, a pattern with a decimal point and no '0' at all (\"#.##\") shows one integer digit\n minInt: !mantissa.includes('0') && mantissa.includes('.') ? 1 : [...intPart].filter((c) => c === '0').length,\n minFrac: [...fracPart].filter((c) => c === '0').length,\n maxFrac: [...fracPart].filter((c) => c === '0' || c === '#').length,\n grouping: lastComma === -1 ? 0 : intPart.length - lastComma - 1,\n percent,\n exponent: exp === undefined ? null : exp.length,\n hasDigits: /[0#]/.test(mantissa),\n };\n patterns.set(pattern, parsed);\n return parsed;\n}\n\n/** Decimal digits of |x|: value = 0.d1d2d3... \u00D7 10^intLen (no leading zero digit; \"\" for 0). */\ninterface Digits {\n digits: string;\n intLen: number;\n}\n\nfunction shortestDigits(x: number): Digits {\n const m = /^(\\d+)(?:\\.(\\d+))?(?:e([+-]\\d+))?$/.exec(String(Math.abs(x)))!;\n const all = m[1]! + (m[2] ?? '');\n let intLen = m[1]!.length + Number(m[3] ?? 0);\n const lead = all.length - all.replace(/^0+/, '').length;\n intLen -= lead;\n const digits = all.slice(lead).replace(/0+$/, '');\n return { digits, intLen: digits ? intLen : 0 };\n}\n\nconst bitsView = new DataView(new ArrayBuffer(8));\n\n/** Exact decimal expansion of the double |x|. */\nfunction exactDigits(x: number): Digits {\n const abs = Math.abs(x);\n if (abs === 0) return { digits: '', intLen: 0 };\n // an integer below 2^53 prints exactly\n if (Number.isSafeInteger(abs)) {\n const str = String(abs);\n return { digits: trimZeros(str), intLen: str.length };\n }\n bitsView.setFloat64(0, abs);\n const bits = bitsView.getBigUint64(0);\n const expBits = Number((bits >> 52n) & 0x7ffn);\n let mant = bits & 0xfffffffffffffn;\n const e2 = expBits === 0 ? -1074 : expBits - 1075;\n if (expBits !== 0) mant |= 1n << 52n;\n // the digits of mant \u00D7 2^e2 (mant \u00D7 5^-e2 / 10^-e2 when e2 < 0); mant is not 0, so no leading zero\n const str = (e2 >= 0 ? mant << BigInt(e2) : mant * pow5(-e2)).toString();\n return { digits: trimZeros(str), intLen: str.length - Math.max(0, -e2) };\n}\n\n/** Rounds to `frac` digits after the point. */\nfunction roundDigits(d: Digits, frac: number, mode: Rounding): Digits {\n const keep = d.intLen + frac;\n if (keep >= d.digits.length) return d;\n if (keep < 0) return { digits: '', intLen: 0 };\n const first = d.digits.charCodeAt(keep) - 48;\n let up: boolean;\n if (mode !== 'halfEvenExact') up = first >= 5;\n else if (first !== 5) up = first > 5;\n else if (d.digits.length > keep + 1) up = true;\n else up = keep > 0 && (d.digits.charCodeAt(keep - 1) - 48) % 2 === 1;\n let kept = d.digits.slice(0, keep);\n let intLen = d.intLen;\n if (up) {\n const n = (BigInt(kept || '0') + 1n).toString();\n if (n.length > kept.length) intLen += 1;\n kept = n;\n }\n kept = kept.replace(/0+$/, '');\n return { digits: kept, intLen: kept ? intLen : 0 };\n}\n\nfunction group(int: string, size: number): string {\n if (!size || int.length <= size) return int;\n const parts: string[] = [];\n for (let end = int.length; end > 0; end -= size) parts.unshift(int.slice(Math.max(0, end - size), end));\n return parts.join(',');\n}\n\nfunction layout(d: Digits, p: Pattern): string {\n let int = d.intLen > 0 ? d.digits.slice(0, d.intLen).padEnd(d.intLen, '0') : '';\n int = int.replace(/^0+/, '').padStart(p.minInt, '0');\n let frac = d.intLen < 0 ? '0'.repeat(-d.intLen) + d.digits : d.digits.slice(Math.max(0, d.intLen));\n frac = frac.slice(0, p.maxFrac).replace(/0+$/, '').padEnd(p.minFrac, '0');\n if (!int && !frac) int = '0';\n return group(int, p.grouping) + (frac ? '.' + frac : '');\n}\n\n/** Formats a number with a DecimalFormat pattern. */\nexport function formatNumber(value: number, pattern: string, mode: Rounding): string {\n if (Number.isNaN(value)) return 'NaN';\n const p = parsePattern(pattern);\n if (!Number.isFinite(value)) return affixes(p, value < 0, '\u221E');\n const x = p.percent ? value * 100 : value;\n const toDigits = mode === 'halfUpShortest' ? shortestDigits : exactDigits;\n\n let body: string;\n let isZero: boolean;\n if (p.exponent !== null) {\n const rounded = roundDigits(toDigits(x), p.maxFrac, mode);\n const intDigits = Math.max(p.minInt, 1);\n isZero = rounded.digits === '';\n let exponent = isZero ? 0 : rounded.intLen - intDigits;\n let mant = roundDigits({ digits: rounded.digits, intLen: isZero ? 0 : intDigits }, p.maxFrac, mode);\n if (mant.intLen > intDigits) {\n exponent += 1;\n mant = { digits: mant.digits, intLen: intDigits };\n }\n const e = String(Math.abs(exponent)).padStart(p.exponent, '0');\n body = layout(mant, p) + 'E' + (exponent < 0 ? '-' : '') + e;\n } else {\n // 16 decimals at most from 1e-3 up (the shortest digits of a double have no more there)\n const frac = !p.hasDigits ? 0 : Math.abs(x) >= 1e-3 ? Math.min(p.maxFrac, 16) : p.maxFrac;\n const rounded = mode === 'halfEvenConverted' ? javaFixedDigits(x, frac) : roundDigits(toDigits(x), frac, mode);\n isZero = rounded.digits === '';\n body = p.hasDigits ? layout(rounded, p) : layout(rounded, { ...p, minInt: 0, maxFrac: 0, minFrac: 0 });\n }\n // a negative number that rounds to zero keeps its sign with a percent pattern (\"-0%\", #180)\n return affixes(p, x < 0 && (!isZero || !p.hasDigits || p.percent), body);\n}\n\n/** `body` with the text of the positive pattern, or of the negative one (\"-\" + prefix without \"pos;neg\"). */\nfunction affixes(p: Pattern, negative: boolean, body: string): string {\n if (!negative) return p.prefix + body + p.suffix;\n if (p.negPrefix === null) return '-' + p.prefix + body + p.suffix;\n return p.negPrefix + body + p.negSuffix!;\n}\n\n/**\n * `[minmove, pricescale]` of a tick (PineScript `syminfo.mintick = syminfo.minmove / syminfo.pricescale`).\n * Without `pricescale` it is 10^(decimals of the tick): 0.02 is 2 / 100, 0.25 is 25 / 100. A symbol priced in\n * fractions needs its own (1/32 is 1 / 32).\n */\nexport function tickScale(mintick: number, pricescale?: number): [number, number] {\n if (pricescale === undefined) {\n const m = /^\\d+(?:\\.(\\d+))?(?:e-(\\d+))?$/.exec(String(mintick));\n pricescale = Number(`1e${m ? (m[1]?.length ?? 0) + Number(m[2] ?? 0) : 0}`);\n }\n return [Math.round(mintick * pricescale), pricescale];\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwBA,6BAAiD;AAqBjD,MAAM,WAAW,oBAAI,IAAqB;AAG1C,SAAS,gBAAgB,SAAyB;AAChD,MAAI,SAAS;AACb,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,QAAI,QAAQ,CAAC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S;AAC9C,QAAI,EAAE,SAAS,KAAK,OAAQ,WAAU;AACtC,WAAO;AAAA,EACT;AACA,SAAO,KAAK,QAAQ,OAAO,EAAE;AAC7B,SAAO,EAAE,QAAQ,MAAM,QAAQ,OAAO,SAAS,EAAE;AACnD;AAEA,SAAS,MAAM,KAAa,MAAsB;AAChD,MAAI,CAAC,QAAQ,IAAI,UAAU,KAAM,QAAO;AACxC,QAAM,QAAkB,CAAC;AACzB,WAAS,MAAM,IAAI,QAAQ,MAAM,GAAG,OAAO,KAAM,OAAM,QAAQ,IAAI,MAAM,KAAK,IAAI,GAAG,MAAM,IAAI,GAAG,GAAG,CAAC;AACtG,SAAO,MAAM,KAAK,GAAG;AACvB;AAEA,SAAS,OAAO,GAAW,GAAoB;AAC7C,MAAI,MAAM,EAAE,SAAS,IAAI,EAAE,OAAO,MAAM,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,GAAG,IAAI;AAC7E,QAAM,IAAI,QAAQ,OAAO,EAAE,EAAE,SAAS,EAAE,QAAQ,GAAG;AACnD,MAAI,OAAO,EAAE,SAAS,IAAI,IAAI,OAAO,CAAC,EAAE,MAAM,IAAI,EAAE,SAAS,EAAE,OAAO,MAAM,KAAK,IAAI,GAAG,EAAE,MAAM,CAAC;AACjG,SAAO,KAAK,MAAM,GAAG,EAAE,OAAO,EAAE,QAAQ,OAAO,EAAE,EAAE,OAAO,EAAE,SAAS,GAAG;AACxE,MAAI,CAAC,OAAO,CAAC,KAAM,OAAM;AACzB,SAAO,MAAM,KAAK,EAAE,QAAQ,KAAK,OAAO,MAAM,OAAO;AACvD;
|
|
4
|
+
"sourcesContent": ["/**\n * Number patterns (\"#.##\", \"#,##0.00\", \"0.00E0\", \"#.##%\", \"'#'#.##\") as PineScript formats them.\n *\n * The pattern syntax is Java's DecimalFormat: `0` required digit, `#` optional digit, `,` grouping,\n * `.` decimal point, `E0` exponent, `%` multiplies by 100, `'...'` quoted literal text.\n * PineScript rules:\n * - `str.tostring` with a format rounds half away from zero on the shortest decimal form of the number\n * (`1.005` with \"#.##\" gives \"1.01\", `2.5` with \"#\" gives \"3\")\n * - `str.tostring` without a format rounds the digits of the JVM's binary to decimal conversion to 10 decimals,\n * half to even, the conversion flags deciding a tie (see `floatingdecimal.ts`): 12.34500000005 gives \"12.345\"\n * (\"12.3450000001\" with the format \"#.##########\"), 1791662400001 / 900000 gives \"1990736.000001111\"\n * - `str.format` rounds half to even on the exact binary value (`0.25` with \"#.#\" gives \"0.2\")\n * - a negative number that rounds to zero loses its sign, except with \"%\" (\"#.#%\": -0.0004 gives \"-0%\");\n * \"#.00\" writes `.50` (no leading zero),\n * but \"#.##\" writes `0.5` (a pattern without any '0' shows one integer digit)\n * - with an exponent, the value is first rounded to the fraction digits (\"0.00E0\": 0.125 gives \"1.30E-1\")\n * - a pattern without digit characters (`format.price` is \"price\") formats like \"#\" after its text,\n * and keeps the sign: -0.004 gives \"-price0\"\n * - \"pos;neg\": a negative number uses the text around the digits of the negative subpattern instead of \"-\"\n * (\"#.##;(#.##)\" gives \"(3.5)\" for -3.5); the digits follow the positive subpattern, as in Java\n * - at most 16 decimals when |x| >= 1e-3 (the shortest digits of a double never have more there):\n * 0.1 with 20 '#' decimals gives \"0.1\" in both rounding modes\n */\n\nimport { javaFixedDigits, pow5, trimZeros } from './floatingdecimal.js';\n\nexport type Rounding = 'halfUpShortest' | 'halfUpExact' | 'halfEvenExact' | 'halfEvenConverted';\n\ninterface Pattern {\n prefix: string;\n suffix: string;\n /** Text around the digits of the negative subpattern (\"pos;neg\"), or null without one */\n negPrefix: string | null;\n negSuffix: string | null;\n minInt: number;\n minFrac: number;\n maxFrac: number;\n /** Digits per group, 0 without grouping */\n grouping: number;\n percent: boolean;\n /** Minimum exponent digits, or null without exponent */\n exponent: number | null;\n hasDigits: boolean;\n}\n\nconst patterns = new Map<string, Pattern>();\n\n/** Index of the first ';' outside quotes, or -1. */\nfunction subpatternSplit(pattern: string): number {\n let quoted = false;\n for (let i = 0; i < pattern.length; i++) {\n if (pattern[i] === \"'\") quoted = !quoted;\n else if (pattern[i] === ';' && !quoted) return i;\n }\n return -1;\n}\n\nfunction parsePattern(pattern: string): Pattern {\n const cached = patterns.get(pattern);\n if (cached) return cached;\n const semi = subpatternSplit(pattern);\n if (semi !== -1) {\n // only the text around the digits of the negative subpattern is used\n const neg = parsePattern(pattern.slice(semi + 1));\n const parsed = { ...parsePattern(pattern.slice(0, semi)), negPrefix: neg.prefix, negSuffix: neg.suffix };\n patterns.set(pattern, parsed);\n return parsed;\n }\n\n let prefix = '';\n let suffix = '';\n let number = '';\n let percent = false;\n let phase: 'prefix' | 'number' | 'suffix' = 'prefix';\n for (let i = 0; i < pattern.length; i++) {\n const ch = pattern[i]!;\n let literal: string;\n if (ch === \"'\") {\n const end = pattern.indexOf(\"'\", i + 1);\n if (end === i + 1) {\n literal = \"'\";\n i = end;\n } else {\n literal = pattern.slice(i + 1, end === -1 ? undefined : end);\n i = end === -1 ? pattern.length : end;\n }\n } else if (phase !== 'suffix' && ('#0,.'.includes(ch) || (phase === 'number' && ch === 'E'))) {\n phase = 'number';\n number += ch;\n continue;\n } else {\n if (ch === '%') percent = true;\n literal = ch;\n }\n if (phase === 'number') phase = 'suffix';\n if (phase === 'prefix') prefix += literal;\n else suffix += literal;\n }\n\n const [mantissa = '', exp] = number.split('E');\n const [intPart = '', fracPart = ''] = mantissa.split('.');\n const lastComma = intPart.lastIndexOf(',');\n const parsed: Pattern = {\n prefix,\n suffix,\n negPrefix: null,\n negSuffix: null,\n // as in Java, a pattern with a decimal point and no '0' at all (\"#.##\") shows one integer digit\n minInt: !mantissa.includes('0') && mantissa.includes('.') ? 1 : [...intPart].filter((c) => c === '0').length,\n minFrac: [...fracPart].filter((c) => c === '0').length,\n maxFrac: [...fracPart].filter((c) => c === '0' || c === '#').length,\n grouping: lastComma === -1 ? 0 : intPart.length - lastComma - 1,\n percent,\n exponent: exp === undefined ? null : exp.length,\n hasDigits: /[0#]/.test(mantissa),\n };\n patterns.set(pattern, parsed);\n return parsed;\n}\n\n/** Decimal digits of |x|: value = 0.d1d2d3... \u00D7 10^intLen (no leading zero digit; \"\" for 0). */\ninterface Digits {\n digits: string;\n intLen: number;\n}\n\nfunction shortestDigits(x: number): Digits {\n const m = /^(\\d+)(?:\\.(\\d+))?(?:e([+-]\\d+))?$/.exec(String(Math.abs(x)))!;\n const all = m[1]! + (m[2] ?? '');\n let intLen = m[1]!.length + Number(m[3] ?? 0);\n const lead = all.length - all.replace(/^0+/, '').length;\n intLen -= lead;\n const digits = all.slice(lead).replace(/0+$/, '');\n return { digits, intLen: digits ? intLen : 0 };\n}\n\nconst bitsView = new DataView(new ArrayBuffer(8));\n\n/** Exact decimal expansion of the double |x|. */\nfunction exactDigits(x: number): Digits {\n const abs = Math.abs(x);\n if (abs === 0) return { digits: '', intLen: 0 };\n // an integer below 2^53 prints exactly\n if (Number.isSafeInteger(abs)) {\n const str = String(abs);\n return { digits: trimZeros(str), intLen: str.length };\n }\n bitsView.setFloat64(0, abs);\n const bits = bitsView.getBigUint64(0);\n const expBits = Number((bits >> 52n) & 0x7ffn);\n let mant = bits & 0xfffffffffffffn;\n const e2 = expBits === 0 ? -1074 : expBits - 1075;\n if (expBits !== 0) mant |= 1n << 52n;\n // the digits of mant \u00D7 2^e2 (mant \u00D7 5^-e2 / 10^-e2 when e2 < 0); mant is not 0, so no leading zero\n const str = (e2 >= 0 ? mant << BigInt(e2) : mant * pow5(-e2)).toString();\n return { digits: trimZeros(str), intLen: str.length - Math.max(0, -e2) };\n}\n\n/** Rounds to `frac` digits after the point. */\nfunction roundDigits(d: Digits, frac: number, mode: Rounding): Digits {\n const keep = d.intLen + frac;\n if (keep >= d.digits.length) return d;\n if (keep < 0) return { digits: '', intLen: 0 };\n const first = d.digits.charCodeAt(keep) - 48;\n let up: boolean;\n if (mode !== 'halfEvenExact') up = first >= 5;\n else if (first !== 5) up = first > 5;\n else if (d.digits.length > keep + 1) up = true;\n else up = keep > 0 && (d.digits.charCodeAt(keep - 1) - 48) % 2 === 1;\n let kept = d.digits.slice(0, keep);\n let intLen = d.intLen;\n if (up) {\n const n = (BigInt(kept || '0') + 1n).toString();\n if (n.length > kept.length) intLen += 1;\n kept = n;\n }\n kept = kept.replace(/0+$/, '');\n return { digits: kept, intLen: kept ? intLen : 0 };\n}\n\nfunction group(int: string, size: number): string {\n if (!size || int.length <= size) return int;\n const parts: string[] = [];\n for (let end = int.length; end > 0; end -= size) parts.unshift(int.slice(Math.max(0, end - size), end));\n return parts.join(',');\n}\n\nfunction layout(d: Digits, p: Pattern): string {\n let int = d.intLen > 0 ? d.digits.slice(0, d.intLen).padEnd(d.intLen, '0') : '';\n int = int.replace(/^0+/, '').padStart(p.minInt, '0');\n let frac = d.intLen < 0 ? '0'.repeat(-d.intLen) + d.digits : d.digits.slice(Math.max(0, d.intLen));\n frac = frac.slice(0, p.maxFrac).replace(/0+$/, '').padEnd(p.minFrac, '0');\n if (!int && !frac) int = '0';\n return group(int, p.grouping) + (frac ? '.' + frac : '');\n}\n\n/**\n * Texts already formatted, by rounding mode, pattern and value: a script formats the same values on each run (the\n * whole history again on every update of the last bar). -0 is not kept (a Map does not tell it from 0).\n */\nconst formatted = new Map<Rounding, Map<string, Map<number, string>>>();\nlet formattedCount = 0;\nconst FORMATTED_KEPT = 100_000;\n\n/** Formats a number with a DecimalFormat pattern. */\nexport function formatNumber(value: number, pattern: string, mode: Rounding): string {\n if (Number.isNaN(value) || Object.is(value, -0)) return format(value, pattern, mode);\n let byPattern = formatted.get(mode);\n if (byPattern === undefined) formatted.set(mode, (byPattern = new Map()));\n let byValue = byPattern.get(pattern);\n if (byValue === undefined) byPattern.set(pattern, (byValue = new Map()));\n let text = byValue.get(value);\n if (text === undefined) {\n text = format(value, pattern, mode);\n if (formattedCount >= FORMATTED_KEPT) {\n formatted.clear();\n formattedCount = 0;\n formatted.set(mode, (byPattern = new Map()));\n byPattern.set(pattern, (byValue = new Map()));\n }\n byValue.set(value, text);\n formattedCount++;\n }\n return text;\n}\n\nfunction format(value: number, pattern: string, mode: Rounding): string {\n if (Number.isNaN(value)) return 'NaN';\n const p = parsePattern(pattern);\n if (!Number.isFinite(value)) return affixes(p, value < 0, '\u221E');\n const x = p.percent ? value * 100 : value;\n const toDigits = mode === 'halfUpShortest' ? shortestDigits : exactDigits;\n\n let body: string;\n let isZero: boolean;\n if (p.exponent !== null) {\n const rounded = roundDigits(toDigits(x), p.maxFrac, mode);\n const intDigits = Math.max(p.minInt, 1);\n isZero = rounded.digits === '';\n let exponent = isZero ? 0 : rounded.intLen - intDigits;\n let mant = roundDigits({ digits: rounded.digits, intLen: isZero ? 0 : intDigits }, p.maxFrac, mode);\n if (mant.intLen > intDigits) {\n exponent += 1;\n mant = { digits: mant.digits, intLen: intDigits };\n }\n const e = String(Math.abs(exponent)).padStart(p.exponent, '0');\n body = layout(mant, p) + 'E' + (exponent < 0 ? '-' : '') + e;\n } else {\n // 16 decimals at most from 1e-3 up (the shortest digits of a double have no more there)\n const frac = !p.hasDigits ? 0 : Math.abs(x) >= 1e-3 ? Math.min(p.maxFrac, 16) : p.maxFrac;\n const rounded = mode === 'halfEvenConverted' ? javaFixedDigits(x, frac) : roundDigits(toDigits(x), frac, mode);\n isZero = rounded.digits === '';\n body = p.hasDigits ? layout(rounded, p) : layout(rounded, { ...p, minInt: 0, maxFrac: 0, minFrac: 0 });\n }\n // a negative number that rounds to zero keeps its sign with a percent pattern (\"-0%\", #180)\n return affixes(p, x < 0 && (!isZero || !p.hasDigits || p.percent), body);\n}\n\n/** `body` with the text of the positive pattern, or of the negative one (\"-\" + prefix without \"pos;neg\"). */\nfunction affixes(p: Pattern, negative: boolean, body: string): string {\n if (!negative) return p.prefix + body + p.suffix;\n if (p.negPrefix === null) return '-' + p.prefix + body + p.suffix;\n return p.negPrefix + body + p.negSuffix!;\n}\n\n/**\n * `[minmove, pricescale]` of a tick (PineScript `syminfo.mintick = syminfo.minmove / syminfo.pricescale`).\n * Without `pricescale` it is 10^(decimals of the tick): 0.02 is 2 / 100, 0.25 is 25 / 100. A symbol priced in\n * fractions needs its own (1/32 is 1 / 32).\n */\nexport function tickScale(mintick: number, pricescale?: number): [number, number] {\n if (pricescale === undefined) {\n const m = /^\\d+(?:\\.(\\d+))?(?:e-(\\d+))?$/.exec(String(mintick));\n pricescale = Number(`1e${m ? (m[1]?.length ?? 0) + Number(m[2] ?? 0) : 0}`);\n }\n return [Math.round(mintick * pricescale), pricescale];\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwBA,6BAAiD;AAqBjD,MAAM,WAAW,oBAAI,IAAqB;AAG1C,SAAS,gBAAgB,SAAyB;AAChD,MAAI,SAAS;AACb,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,QAAI,QAAQ,CAAC,MAAM,IAAK,UAAS,CAAC;AAAA,aACzB,QAAQ,CAAC,MAAM,OAAO,CAAC,OAAQ,QAAO;AAAA,EACjD;AACA,SAAO;AACT;AAEA,SAAS,aAAa,SAA0B;AAC9C,QAAM,SAAS,SAAS,IAAI,OAAO;AACnC,MAAI,OAAQ,QAAO;AACnB,QAAM,OAAO,gBAAgB,OAAO;AACpC,MAAI,SAAS,IAAI;AAEf,UAAM,MAAM,aAAa,QAAQ,MAAM,OAAO,CAAC,CAAC;AAChD,UAAMA,UAAS,EAAE,GAAG,aAAa,QAAQ,MAAM,GAAG,IAAI,CAAC,GAAG,WAAW,IAAI,QAAQ,WAAW,IAAI,OAAO;AACvG,aAAS,IAAI,SAASA,OAAM;AAC5B,WAAOA;AAAA,EACT;AAEA,MAAI,SAAS;AACb,MAAI,SAAS;AACb,MAAI,SAAS;AACb,MAAI,UAAU;AACd,MAAI,QAAwC;AAC5C,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,KAAK,QAAQ,CAAC;AACpB,QAAI;AACJ,QAAI,OAAO,KAAK;AACd,YAAM,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AC,SAAU,QAAO,EAAE,SAAS,OAAO,EAAE;AAC1C,MAAI,EAAE,cAAc,KAAM,QAAO,MAAM,EAAE,SAAS,OAAO,EAAE;AAC3D,SAAO,EAAE,YAAY,OAAO,EAAE;AAChC;AAOO,SAAS,UAAU,SAAiB,YAAuC;AAChF,MAAI,eAAe,QAAW;AAC5B,UAAM,IAAI,gCAAgC,KAAK,OAAO,OAAO,CAAC;AAC9D,iBAAa,OAAO,KAAK,KAAK,EAAE,CAAC,GAAG,UAAU,KAAK,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE;AAAA,EAC5E;AACA,SAAO,CAAC,KAAK,MAAM,UAAU,UAAU,GAAG,UAAU;AACtD;",
|
|
6
6
|
"names": ["parsed", "str"]
|
|
7
7
|
}
|
|
@@ -244,5 +244,13 @@ export interface StrategyEngine {
|
|
|
244
244
|
risk?(rule: StrategyRiskRule): void;
|
|
245
245
|
/** `strategy.default_entry_qty(fill_price)`; optional. */
|
|
246
246
|
defaultEntryQty?(fillPrice: number): number;
|
|
247
|
+
/**
|
|
248
|
+
* The engine state at the end of a bar (orders, positions, trades, equity), for an incremental script run
|
|
249
|
+
* (createScriptRun, #196); optional. With {@link restore}, a live update of a strategy calculates the newest bars
|
|
250
|
+
* only: the engine of the next run gets the state of the last confirmed bar. Without them, every update is a full run.
|
|
251
|
+
*/
|
|
252
|
+
save?(): unknown;
|
|
253
|
+
/** Puts back a state given by {@link save} (on a new engine of the same script and bars). */
|
|
254
|
+
restore?(state: unknown): void;
|
|
247
255
|
}
|
|
248
256
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/strategy/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,OAAO,CAAC;AACjD,MAAM,MAAM,eAAe,GAAG,OAAO,GAAG,MAAM,GAAG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,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,GAAG,SAAS,CAAC;IACtD,yCAAyC;IACzC,IAAI,CAAC,CAAC,IAAI,EAAE,gBAAgB,GAAG,IAAI,CAAC;IACpC,0DAA0D;IAC1D,eAAe,CAAC,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAAC;IAC5C;;;;OAIG;IACH,IAAI,CAAC,IAAI,OAAO,CAAC;IACjB,6FAA6F;IAC7F,OAAO,CAAC,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;CAChC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/strategy/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Types and constants of the PineScript `strategy.*` API.\n *\n * OakScriptJS does not simulate orders. The script API (`oakscriptjs/script`) declares the strategy,\n * forwards every `strategy.*` call to a {@link StrategyEngine} that the host supplies, and reads the\n * `strategy.*` variables from it. The engine fills the orders, keeps the trades and computes the\n * results.\n *\n * Names follow PineScript v6: option objects use the PineScript argument names, and the engine\n * receives them unchanged. An `na` (NaN) numeric argument is removed before the call, since in\n * PineScript it means \"not given\". The deprecated `when` argument does not exist: use `if`.\n *\n * @module strategy\n */\n\nexport type StrategyDirection = 'long' | 'short';\nexport type StrategyQtyType = 'fixed' | 'cash' | 'percent_of_equity';\nexport type StrategyCommissionType = 'percent' | 'cash_per_contract' | 'cash_per_order';\nexport type StrategyOcaType = 'none' | 'cancel' | 'reduce';\n/** `strategy.direction.*`, for `strategy.risk.allow_entry_in`. */\nexport type StrategyRiskDirection = 'all' | 'long' | 'short';\nexport type StrategyRiskValueType = 'percent_of_equity' | 'cash';\n\n/** PineScript `strategy.*` constants. */\nexport const STRATEGY_CONSTANTS = {\n long: 'long',\n short: 'short',\n fixed: 'fixed',\n cash: 'cash',\n percent_of_equity: 'percent_of_equity',\n commission: { percent: 'percent', cash_per_contract: 'cash_per_contract', cash_per_order: 'cash_per_order' },\n direction: { all: 'all', long: 'long', short: 'short' },\n oca: { none: 'none', cancel: 'cancel', reduce: 'reduce' },\n} as const;\n\n/** Arguments of the PineScript `strategy()` declaration, after `title`. */\nexport interface StrategyOptions {\n shorttitle?: string;\n overlay?: boolean;\n format?: string;\n precision?: number;\n scale?: string;\n pyramiding?: number;\n calc_on_order_fills?: boolean;\n calc_on_every_tick?: boolean;\n /** Runs the strategy on each tick of the history bars too (the reference app's \"On history bar tick\"). */\n calc_on_every_history_tick?: boolean;\n max_bars_back?: number;\n backtest_fill_limits_assumption?: number;\n default_qty_type?: StrategyQtyType;\n default_qty_value?: number;\n initial_capital?: number;\n /** Account currency; default: the symbol currency. */\n currency?: string;\n /** Ticks added to market and stop fills. */\n slippage?: number;\n commission_type?: StrategyCommissionType;\n commission_value?: number;\n process_orders_on_close?: boolean;\n close_entries_rule?: 'FIFO' | 'ANY';\n margin_long?: number;\n margin_short?: number;\n explicit_plot_zorder?: boolean;\n max_lines_count?: number;\n max_labels_count?: number;\n max_boxes_count?: number;\n calc_bars_count?: number;\n risk_free_rate?: number;\n use_bar_magnifier?: boolean;\n fill_orders_on_standard_ohlc?: boolean;\n max_polylines_count?: number;\n}\n\n/** Strategy properties passed to the engine: the declared values, else the PineScript defaults. */\nexport interface StrategyProperties {\n pyramiding: number;\n calc_on_order_fills: boolean;\n calc_on_every_tick: boolean;\n calc_on_every_history_tick: boolean;\n backtest_fill_limits_assumption: number;\n default_qty_type: StrategyQtyType;\n default_qty_value: number;\n initial_capital: number;\n /** undefined: the symbol currency. */\n currency?: string;\n slippage: number;\n commission_type: StrategyCommissionType;\n commission_value: number;\n process_orders_on_close: boolean;\n close_entries_rule: 'FIFO' | 'ANY';\n margin_long: number;\n margin_short: number;\n calc_bars_count: number;\n risk_free_rate: number;\n use_bar_magnifier: boolean;\n fill_orders_on_standard_ohlc: boolean;\n}\n\n/** PineScript defaults of the `strategy()` arguments (v6 reference). */\nexport const STRATEGY_DEFAULTS: StrategyProperties = {\n pyramiding: 0,\n calc_on_order_fills: false,\n calc_on_every_tick: false,\n calc_on_every_history_tick: false,\n backtest_fill_limits_assumption: 0,\n // v6 values; PineScript v5: fixed / 1 / 1000000 and margins 0\n default_qty_type: 'percent_of_equity',\n default_qty_value: 100,\n initial_capital: 100000,\n slippage: 0,\n commission_type: 'percent',\n commission_value: 0,\n process_orders_on_close: false,\n close_entries_rule: 'FIFO',\n margin_long: 100,\n margin_short: 100,\n calc_bars_count: 0,\n risk_free_rate: 2,\n use_bar_magnifier: false,\n fill_orders_on_standard_ohlc: false,\n};\n\n/** `strategy.entry()` / `strategy.order()` arguments after `id` and `direction`. */\nexport interface StrategyEntryOptions {\n qty?: number;\n limit?: number;\n stop?: number;\n oca_name?: string;\n oca_type?: StrategyOcaType;\n comment?: string;\n alert_message?: string;\n disable_alert?: boolean;\n}\n\n/** `strategy.exit()` arguments after `id`. `profit`, `loss`, `trail_points` and `trail_offset` are in ticks. */\nexport interface StrategyExitOptions {\n from_entry?: string;\n qty?: number;\n qty_percent?: number;\n profit?: number;\n limit?: number;\n loss?: number;\n stop?: number;\n trail_price?: number;\n trail_points?: number;\n trail_offset?: number;\n oca_name?: string;\n comment?: string;\n comment_profit?: string;\n comment_loss?: string;\n comment_trailing?: string;\n alert_message?: string;\n alert_profit?: string;\n alert_loss?: string;\n alert_trailing?: string;\n disable_alert?: boolean;\n}\n\n/** `strategy.close()` arguments after `id`. */\nexport interface StrategyCloseOptions {\n comment?: string;\n qty?: number;\n qty_percent?: number;\n alert_message?: string;\n immediately?: boolean;\n disable_alert?: boolean;\n}\n\n/** `strategy.close_all()` arguments. */\nexport interface StrategyCloseAllOptions {\n comment?: string;\n alert_message?: string;\n immediately?: boolean;\n disable_alert?: boolean;\n}\n\n/** A `strategy.risk.*` rule. */\nexport type StrategyRiskRule =\n | { rule: 'allow_entry_in'; direction: StrategyRiskDirection }\n | { rule: 'max_cons_loss_days'; count: number; alert_message?: string }\n | { rule: 'max_drawdown'; value: number; type: StrategyRiskValueType; alert_message?: string }\n | { rule: 'max_intraday_filled_orders'; count: number; alert_message?: string }\n | { rule: 'max_intraday_loss'; value: number; type: StrategyRiskValueType; alert_message?: string }\n | { rule: 'max_position_size'; contracts: number };\n\n/**\n * One trade, as the PineScript `strategy.opentrades.*(i)` / `strategy.closedtrades.*(i)` functions\n * return it. Times are UNIX milliseconds. The `exit_*` fields are for closed trades only; `exit_id` and the\n * comments are undefined when the engine does not provide them.\n */\nexport interface StrategyTrade {\n entry_id: string;\n entry_price: number;\n entry_bar_index: number;\n entry_time: number;\n /** undefined when the order had no comment, or when the engine does not keep it apart from the id. */\n entry_comment?: string;\n /** Signed quantity: positive for a long trade, negative for a short trade. */\n size: number;\n profit: number;\n profit_percent: number;\n commission: number;\n max_runup: number;\n max_runup_percent: number;\n max_drawdown: number;\n max_drawdown_percent: number;\n exit_id?: string;\n exit_price?: number;\n exit_bar_index?: number;\n exit_time?: number;\n exit_comment?: string;\n}\n\n/** Numeric `strategy.*` variables. */\nexport const STRATEGY_NUMBER_VARIABLES = [\n 'position_size',\n 'position_avg_price',\n 'equity',\n 'initial_capital',\n 'netprofit',\n 'netprofit_percent',\n 'openprofit',\n 'openprofit_percent',\n 'grossprofit',\n 'grossprofit_percent',\n 'grossloss',\n 'grossloss_percent',\n 'opentrades',\n 'closedtrades',\n 'wintrades',\n 'losstrades',\n 'eventrades',\n 'avg_trade',\n 'avg_trade_percent',\n 'avg_winning_trade',\n 'avg_winning_trade_percent',\n 'avg_losing_trade',\n 'avg_losing_trade_percent',\n 'max_drawdown',\n 'max_drawdown_percent',\n 'max_runup',\n 'max_runup_percent',\n 'max_contracts_held_all',\n 'max_contracts_held_long',\n 'max_contracts_held_short',\n 'margin_liquidation_price',\n] as const;\n\n/** Text `strategy.*` variables. */\nexport const STRATEGY_TEXT_VARIABLES = ['position_entry_name', 'account_currency'] as const;\n\nexport type StrategyNumberVariable = (typeof STRATEGY_NUMBER_VARIABLES)[number];\nexport type StrategyTextVariable = (typeof STRATEGY_TEXT_VARIABLES)[number];\nexport type StrategyVariable = StrategyNumberVariable | StrategyTextVariable;\n\n/**\n * The order engine the host supplies. OakScriptJS calls it in this order on each bar `i` of\n * `strategy.eachBar()`:\n *\n * 1. `processBar(i)`: fill the orders placed before bar `i` (at the open and inside the bar);\n * 2. the script runs at the close of bar `i`: order calls and variable reads;\n * 3. `processClose(i)`: after the script; with `process_orders_on_close`, fill the new market orders\n * at the close.\n */\nexport interface StrategyEngine {\n processBar(bar: number): void;\n processClose(bar: number): void;\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 /** Current value of a `strategy.*` variable; undefined when the engine does not provide it. */\n get(variable: StrategyVariable): number | string | undefined;\n /** Open trade number `index` (0 = oldest); undefined when it does not exist. */\n openTrade(index: number): StrategyTrade | undefined;\n /** Closed trade number `index` (0 = oldest); undefined when it does not exist. */\n closedTrade(index: number): StrategyTrade | undefined;\n /** `strategy.risk.*` rules; optional. */\n risk?(rule: StrategyRiskRule): void;\n /** `strategy.default_entry_qty(fill_price)`; optional. */\n defaultEntryQty?(fillPrice: number): number;\n}\n"],
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Types and constants of the PineScript `strategy.*` API.\n *\n * OakScriptJS does not simulate orders. The script API (`oakscriptjs/script`) declares the strategy,\n * forwards every `strategy.*` call to a {@link StrategyEngine} that the host supplies, and reads the\n * `strategy.*` variables from it. The engine fills the orders, keeps the trades and computes the\n * results.\n *\n * Names follow PineScript v6: option objects use the PineScript argument names, and the engine\n * receives them unchanged. An `na` (NaN) numeric argument is removed before the call, since in\n * PineScript it means \"not given\". The deprecated `when` argument does not exist: use `if`.\n *\n * @module strategy\n */\n\nexport type StrategyDirection = 'long' | 'short';\nexport type StrategyQtyType = 'fixed' | 'cash' | 'percent_of_equity';\nexport type StrategyCommissionType = 'percent' | 'cash_per_contract' | 'cash_per_order';\nexport type StrategyOcaType = 'none' | 'cancel' | 'reduce';\n/** `strategy.direction.*`, for `strategy.risk.allow_entry_in`. */\nexport type StrategyRiskDirection = 'all' | 'long' | 'short';\nexport type StrategyRiskValueType = 'percent_of_equity' | 'cash';\n\n/** PineScript `strategy.*` constants. */\nexport const STRATEGY_CONSTANTS = {\n long: 'long',\n short: 'short',\n fixed: 'fixed',\n cash: 'cash',\n percent_of_equity: 'percent_of_equity',\n commission: { percent: 'percent', cash_per_contract: 'cash_per_contract', cash_per_order: 'cash_per_order' },\n direction: { all: 'all', long: 'long', short: 'short' },\n oca: { none: 'none', cancel: 'cancel', reduce: 'reduce' },\n} as const;\n\n/** Arguments of the PineScript `strategy()` declaration, after `title`. */\nexport interface StrategyOptions {\n shorttitle?: string;\n overlay?: boolean;\n format?: string;\n precision?: number;\n scale?: string;\n pyramiding?: number;\n calc_on_order_fills?: boolean;\n calc_on_every_tick?: boolean;\n /** Runs the strategy on each tick of the history bars too (the reference app's \"On history bar tick\"). */\n calc_on_every_history_tick?: boolean;\n max_bars_back?: number;\n backtest_fill_limits_assumption?: number;\n default_qty_type?: StrategyQtyType;\n default_qty_value?: number;\n initial_capital?: number;\n /** Account currency; default: the symbol currency. */\n currency?: string;\n /** Ticks added to market and stop fills. */\n slippage?: number;\n commission_type?: StrategyCommissionType;\n commission_value?: number;\n process_orders_on_close?: boolean;\n close_entries_rule?: 'FIFO' | 'ANY';\n margin_long?: number;\n margin_short?: number;\n explicit_plot_zorder?: boolean;\n max_lines_count?: number;\n max_labels_count?: number;\n max_boxes_count?: number;\n calc_bars_count?: number;\n risk_free_rate?: number;\n use_bar_magnifier?: boolean;\n fill_orders_on_standard_ohlc?: boolean;\n max_polylines_count?: number;\n}\n\n/** Strategy properties passed to the engine: the declared values, else the PineScript defaults. */\nexport interface StrategyProperties {\n pyramiding: number;\n calc_on_order_fills: boolean;\n calc_on_every_tick: boolean;\n calc_on_every_history_tick: boolean;\n backtest_fill_limits_assumption: number;\n default_qty_type: StrategyQtyType;\n default_qty_value: number;\n initial_capital: number;\n /** undefined: the symbol currency. */\n currency?: string;\n slippage: number;\n commission_type: StrategyCommissionType;\n commission_value: number;\n process_orders_on_close: boolean;\n close_entries_rule: 'FIFO' | 'ANY';\n margin_long: number;\n margin_short: number;\n calc_bars_count: number;\n risk_free_rate: number;\n use_bar_magnifier: boolean;\n fill_orders_on_standard_ohlc: boolean;\n}\n\n/** PineScript defaults of the `strategy()` arguments (v6 reference). */\nexport const STRATEGY_DEFAULTS: StrategyProperties = {\n pyramiding: 0,\n calc_on_order_fills: false,\n calc_on_every_tick: false,\n calc_on_every_history_tick: false,\n backtest_fill_limits_assumption: 0,\n // v6 values; PineScript v5: fixed / 1 / 1000000 and margins 0\n default_qty_type: 'percent_of_equity',\n default_qty_value: 100,\n initial_capital: 100000,\n slippage: 0,\n commission_type: 'percent',\n commission_value: 0,\n process_orders_on_close: false,\n close_entries_rule: 'FIFO',\n margin_long: 100,\n margin_short: 100,\n calc_bars_count: 0,\n risk_free_rate: 2,\n use_bar_magnifier: false,\n fill_orders_on_standard_ohlc: false,\n};\n\n/** `strategy.entry()` / `strategy.order()` arguments after `id` and `direction`. */\nexport interface StrategyEntryOptions {\n qty?: number;\n limit?: number;\n stop?: number;\n oca_name?: string;\n oca_type?: StrategyOcaType;\n comment?: string;\n alert_message?: string;\n disable_alert?: boolean;\n}\n\n/** `strategy.exit()` arguments after `id`. `profit`, `loss`, `trail_points` and `trail_offset` are in ticks. */\nexport interface StrategyExitOptions {\n from_entry?: string;\n qty?: number;\n qty_percent?: number;\n profit?: number;\n limit?: number;\n loss?: number;\n stop?: number;\n trail_price?: number;\n trail_points?: number;\n trail_offset?: number;\n oca_name?: string;\n comment?: string;\n comment_profit?: string;\n comment_loss?: string;\n comment_trailing?: string;\n alert_message?: string;\n alert_profit?: string;\n alert_loss?: string;\n alert_trailing?: string;\n disable_alert?: boolean;\n}\n\n/** `strategy.close()` arguments after `id`. */\nexport interface StrategyCloseOptions {\n comment?: string;\n qty?: number;\n qty_percent?: number;\n alert_message?: string;\n immediately?: boolean;\n disable_alert?: boolean;\n}\n\n/** `strategy.close_all()` arguments. */\nexport interface StrategyCloseAllOptions {\n comment?: string;\n alert_message?: string;\n immediately?: boolean;\n disable_alert?: boolean;\n}\n\n/** A `strategy.risk.*` rule. */\nexport type StrategyRiskRule =\n | { rule: 'allow_entry_in'; direction: StrategyRiskDirection }\n | { rule: 'max_cons_loss_days'; count: number; alert_message?: string }\n | { rule: 'max_drawdown'; value: number; type: StrategyRiskValueType; alert_message?: string }\n | { rule: 'max_intraday_filled_orders'; count: number; alert_message?: string }\n | { rule: 'max_intraday_loss'; value: number; type: StrategyRiskValueType; alert_message?: string }\n | { rule: 'max_position_size'; contracts: number };\n\n/**\n * One trade, as the PineScript `strategy.opentrades.*(i)` / `strategy.closedtrades.*(i)` functions\n * return it. Times are UNIX milliseconds. The `exit_*` fields are for closed trades only; `exit_id` and the\n * comments are undefined when the engine does not provide them.\n */\nexport interface StrategyTrade {\n entry_id: string;\n entry_price: number;\n entry_bar_index: number;\n entry_time: number;\n /** undefined when the order had no comment, or when the engine does not keep it apart from the id. */\n entry_comment?: string;\n /** Signed quantity: positive for a long trade, negative for a short trade. */\n size: number;\n profit: number;\n profit_percent: number;\n commission: number;\n max_runup: number;\n max_runup_percent: number;\n max_drawdown: number;\n max_drawdown_percent: number;\n exit_id?: string;\n exit_price?: number;\n exit_bar_index?: number;\n exit_time?: number;\n exit_comment?: string;\n}\n\n/** Numeric `strategy.*` variables. */\nexport const STRATEGY_NUMBER_VARIABLES = [\n 'position_size',\n 'position_avg_price',\n 'equity',\n 'initial_capital',\n 'netprofit',\n 'netprofit_percent',\n 'openprofit',\n 'openprofit_percent',\n 'grossprofit',\n 'grossprofit_percent',\n 'grossloss',\n 'grossloss_percent',\n 'opentrades',\n 'closedtrades',\n 'wintrades',\n 'losstrades',\n 'eventrades',\n 'avg_trade',\n 'avg_trade_percent',\n 'avg_winning_trade',\n 'avg_winning_trade_percent',\n 'avg_losing_trade',\n 'avg_losing_trade_percent',\n 'max_drawdown',\n 'max_drawdown_percent',\n 'max_runup',\n 'max_runup_percent',\n 'max_contracts_held_all',\n 'max_contracts_held_long',\n 'max_contracts_held_short',\n 'margin_liquidation_price',\n] as const;\n\n/** Text `strategy.*` variables. */\nexport const STRATEGY_TEXT_VARIABLES = ['position_entry_name', 'account_currency'] as const;\n\nexport type StrategyNumberVariable = (typeof STRATEGY_NUMBER_VARIABLES)[number];\nexport type StrategyTextVariable = (typeof STRATEGY_TEXT_VARIABLES)[number];\nexport type StrategyVariable = StrategyNumberVariable | StrategyTextVariable;\n\n/**\n * The order engine the host supplies. OakScriptJS calls it in this order on each bar `i` of\n * `strategy.eachBar()`:\n *\n * 1. `processBar(i)`: fill the orders placed before bar `i` (at the open and inside the bar);\n * 2. the script runs at the close of bar `i`: order calls and variable reads;\n * 3. `processClose(i)`: after the script; with `process_orders_on_close`, fill the new market orders\n * at the close.\n */\nexport interface StrategyEngine {\n processBar(bar: number): void;\n processClose(bar: number): void;\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 /** Current value of a `strategy.*` variable; undefined when the engine does not provide it. */\n get(variable: StrategyVariable): number | string | undefined;\n /** Open trade number `index` (0 = oldest); undefined when it does not exist. */\n openTrade(index: number): StrategyTrade | undefined;\n /** Closed trade number `index` (0 = oldest); undefined when it does not exist. */\n closedTrade(index: number): StrategyTrade | undefined;\n /** `strategy.risk.*` rules; optional. */\n risk?(rule: StrategyRiskRule): void;\n /** `strategy.default_entry_qty(fill_price)`; optional. */\n defaultEntryQty?(fillPrice: number): number;\n /**\n * The engine state at the end of a bar (orders, positions, trades, equity), for an incremental script run\n * (createScriptRun, #196); optional. With {@link restore}, a live update of a strategy calculates the newest bars\n * only: the engine of the next run gets the state of the last confirmed bar. Without them, every update is a full run.\n */\n save?(): unknown;\n /** Puts back a state given by {@link save} (on a new engine of the same script and bars). */\n restore?(state: unknown): void;\n}\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwBO,MAAM,qBAAqB;AAAA,EAChC,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AAAA,EACP,MAAM;AAAA,EACN,mBAAmB;AAAA,EACnB,YAAY,EAAE,SAAS,WAAW,mBAAmB,qBAAqB,gBAAgB,iBAAiB;AAAA,EAC3G,WAAW,EAAE,KAAK,OAAO,MAAM,QAAQ,OAAO,QAAQ;AAAA,EACtD,KAAK,EAAE,MAAM,QAAQ,QAAQ,UAAU,QAAQ,SAAS;AAC1D;AAkEO,MAAM,oBAAwC;AAAA,EACnD,YAAY;AAAA,EACZ,qBAAqB;AAAA,EACrB,oBAAoB;AAAA,EACpB,4BAA4B;AAAA,EAC5B,iCAAiC;AAAA;AAAA,EAEjC,kBAAkB;AAAA,EAClB,mBAAmB;AAAA,EACnB,iBAAiB;AAAA,EACjB,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,kBAAkB;AAAA,EAClB,yBAAyB;AAAA,EACzB,oBAAoB;AAAA,EACpB,aAAa;AAAA,EACb,cAAc;AAAA,EACd,iBAAiB;AAAA,EACjB,gBAAgB;AAAA,EAChB,mBAAmB;AAAA,EACnB,8BAA8B;AAChC;AA8FO,MAAM,4BAA4B;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,MAAM,0BAA0B,CAAC,uBAAuB,kBAAkB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"running-sum.d.ts","sourceRoot":"","sources":["../../../src/ta/running-sum.ts"],"names":[],"mappings":"AAiBA,8EAA8E;AAC9E,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAE1D;
|
|
1
|
+
{"version":3,"file":"running-sum.d.ts","sourceRoot":"","sources":["../../../src/ta/running-sum.ts"],"names":[],"mappings":"AAiBA,8EAA8E;AAC9E,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAE1D;AA4CD;;;;;;;GAOG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgB;IACvC,mEAAmE;IACnE,OAAO,CAAC,QAAQ,CAAgB;IAChC,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,KAAK,CAAO;IACpB,OAAO,CAAC,YAAY,CAAgB;IACpC;;;;OAIG;IACH,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAwC;IACxE,OAAO,CAAC,kBAAkB,CAAK;IAE/B,sFAAsF;IACtF,OAAO,CAAC,OAAO;IAcf;;;;;OAKG;IACH,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM;IAUvC;;;;;OAKG;IACH,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM;IAS9B,kEAAkE;IAClE,MAAM,IAAI,IAAI;CAOf;AAeD;;;;;;;GAOG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,SAAS,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAsBjG;AAoED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,SAAS,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,EAC5C,OAAO,EAAE,SAAS,CAAC,MAAM,CAAC,EAC1B,IAAI,SAAa,GAChB,MAAM,EAAE,CAGV;AAuBD;;;GAGG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,SAAS,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,EAC5C,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,OAAO,GACd,MAAM,EAAE,CAGV;AAED,4FAA4F;AAC5F,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,SAAS,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,EAC5C,OAAO,EAAE,SAAS,CAAC,MAAM,CAAC,EAC1B,MAAM,EAAE,OAAO,EACf,IAAI,SAAgB,GACnB,MAAM,EAAE,CAGV"}
|
|
@@ -34,7 +34,11 @@ function addExact(p, x) {
|
|
|
34
34
|
let i = 0;
|
|
35
35
|
for (let j = 0; j < p.length; j++) {
|
|
36
36
|
let y = p[j];
|
|
37
|
-
if (Math.abs(x) < Math.abs(y))
|
|
37
|
+
if (Math.abs(x) < Math.abs(y)) {
|
|
38
|
+
const t = x;
|
|
39
|
+
x = y;
|
|
40
|
+
y = t;
|
|
41
|
+
}
|
|
38
42
|
const hi = x + y;
|
|
39
43
|
const lo = y - (hi - x);
|
|
40
44
|
if (lo !== 0) p[i++] = lo;
|
|
@@ -143,8 +147,73 @@ function sumWindows(source, lengthAt) {
|
|
|
143
147
|
}
|
|
144
148
|
function runningSum(source, length) {
|
|
145
149
|
const len = Math.floor(length);
|
|
146
|
-
|
|
147
|
-
|
|
150
|
+
const n = source.length;
|
|
151
|
+
const out = new Array(n);
|
|
152
|
+
if (!(len >= 1)) return out.fill(NaN);
|
|
153
|
+
const values = [];
|
|
154
|
+
const p = new FixedPartials();
|
|
155
|
+
let last = NaN;
|
|
156
|
+
for (let i = 0; i < n; i++) {
|
|
157
|
+
const v = source[i];
|
|
158
|
+
if (!isNa(v)) {
|
|
159
|
+
const count = values.length;
|
|
160
|
+
if (count >= len) p.add(-values[count - len]);
|
|
161
|
+
p.add(v);
|
|
162
|
+
values.push(v);
|
|
163
|
+
last = count + 1 >= len ? p.round() : NaN;
|
|
164
|
+
}
|
|
165
|
+
out[i] = last;
|
|
166
|
+
}
|
|
167
|
+
return out;
|
|
168
|
+
}
|
|
169
|
+
class FixedPartials {
|
|
170
|
+
p = new Float64Array(64);
|
|
171
|
+
n = 0;
|
|
172
|
+
add(x) {
|
|
173
|
+
const p = this.p;
|
|
174
|
+
const n = this.n;
|
|
175
|
+
let i = 0;
|
|
176
|
+
for (let j = 0; j < n; j++) {
|
|
177
|
+
let y = p[j];
|
|
178
|
+
if (Math.abs(x) < Math.abs(y)) {
|
|
179
|
+
const t = x;
|
|
180
|
+
x = y;
|
|
181
|
+
y = t;
|
|
182
|
+
}
|
|
183
|
+
const hi = x + y;
|
|
184
|
+
const lo = y - (hi - x);
|
|
185
|
+
if (lo !== 0) p[i++] = lo;
|
|
186
|
+
x = hi;
|
|
187
|
+
}
|
|
188
|
+
if (i === p.length) {
|
|
189
|
+
const grown = new Float64Array(p.length * 2);
|
|
190
|
+
grown.set(p);
|
|
191
|
+
this.p = grown;
|
|
192
|
+
}
|
|
193
|
+
this.p[i] = x;
|
|
194
|
+
this.n = i + 1;
|
|
195
|
+
}
|
|
196
|
+
round() {
|
|
197
|
+
const p = this.p;
|
|
198
|
+
let n = this.n;
|
|
199
|
+
if (n === 0) return 0;
|
|
200
|
+
let hi = p[--n];
|
|
201
|
+
while (n > 0) {
|
|
202
|
+
const x = hi;
|
|
203
|
+
const y = p[--n];
|
|
204
|
+
hi = x + y;
|
|
205
|
+
const lo = y - (hi - x);
|
|
206
|
+
if (lo !== 0) {
|
|
207
|
+
if (n > 0 && (lo < 0 && p[n - 1] < 0 || lo > 0 && p[n - 1] > 0)) {
|
|
208
|
+
const y2 = lo * 2;
|
|
209
|
+
const x2 = hi + y2;
|
|
210
|
+
if (y2 === x2 - hi) hi = x2;
|
|
211
|
+
}
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return hi;
|
|
216
|
+
}
|
|
148
217
|
}
|
|
149
218
|
function seriesLengths(lengths, count, name) {
|
|
150
219
|
if (lengths.length < count) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/ta/running-sum.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Window sums of PineScript `math.sum` / `ta.sma` / `ta.stdev` / `ta.variance` / `ta.mfi` (bit for bit).\n *\n * PineScript gives the correctly rounded sum of the window values (the exact sum of the doubles, rounded once), on\n * every bar: `ta.sma` is that sum divided by the length (measured on the reference 05/11/2026, #188: built-in and\n * expression sources, with or without a `ta.stdev` of the same source, constant and series lengths, na values; 0\n * differing bars of 16,550 on BTCUSD 1D and 34,665 on AAPL 1D). The running sum of earlier versions (Kahan steps,\n * #114) gave a small residue on a window of zeros; the reference no longer does.\n *\n * The exact sum is kept as non-overlapping partials (Shewchuk's algorithm, as Python `math.fsum`): adding a value and\n * removing the one that leaves the window (adding its negation) are exact, so a bar costs the values that enter and\n * leave, not the whole window.\n *\n * @internal\n */\nimport { checkSumLength } from './limits.js';\n\n/** A value PineScript treats as na in window functions (also +/-Infinity). */\nexport function isNa(v: number | null | undefined): boolean {\n return v === undefined || v === null || !Number.isFinite(v);\n}\n\n/** Adds `x` to the partials `p` (non-overlapping, increasing magnitude), exactly. */\nfunction addExact(p: number[], x: number): void {\n let i = 0;\n for (let j = 0; j < p.length; j++) {\n let y = p[j]!;\n if (Math.abs(x) < Math.abs(y)) [x, y] = [y, x];\n const hi = x + y;\n const lo = y - (hi - x);\n if (lo !== 0) p[i++] = lo;\n x = hi;\n }\n p.length = i;\n p.push(x);\n}\n\n/** The partials' exact sum rounded once to a double (round half to even), as Python `math.fsum`. */\nfunction roundExact(p: readonly number[]): number {\n let n = p.length;\n if (n === 0) return 0;\n let hi = p[--n]!;\n while (n > 0) {\n const x = hi;\n const y = p[--n]!;\n hi = x + y;\n const lo = y - (hi - x);\n if (lo !== 0) {\n // half-way case: the rest has the same sign, so round away from the tie\n if (n > 0 && ((lo < 0 && p[n - 1]! < 0) || (lo > 0 && p[n - 1]! > 0))) {\n const y2 = lo * 2;\n const x2 = hi + y2;\n if (y2 === x2 - hi) hi = x2;\n }\n break;\n }\n }\n return hi;\n}\n\n/**\n * Window sum state, one value at a time. {@link step} computes the sum with a new value from the kept state without\n * changing it; {@link commit} keeps the last step. So several candidate values can be tried on one bar and only the\n * last one kept (a ta.* call in a loop).\n *\n * The length can change from one step to the next (a series length): the window is then the last `length` values,\n * the values that leave or come back are removed or added exactly.\n */\nexport class RunningSum {\n private readonly values: number[] = [];\n /** Exact sum of the kept window (the last `keptLength` values). */\n private partials: number[] = [];\n private keptLength = 0;\n private stepLength = 0;\n private stepX = NaN;\n private stepPartials: number[] = [];\n /**\n * {@link resized} partials of the kept state by length, until the next {@link commit}: the calls of a loop (several\n * steps on one bar) move the same kept sum to the same lengths. Kept from the second step on, so that one step per\n * bar costs nothing more.\n */\n private readonly resizedByLength = new Map<number, readonly number[]>();\n private resizedSinceCommit = 0;\n\n /** The partials of the last `len` values (kept state, nothing added); a new array. */\n private resized(len: number): number[] {\n const cached = this.resizedByLength.get(len);\n if (cached) return cached.slice();\n const values = this.values;\n const n = values.length;\n const p = this.partials.slice();\n const kept = Math.min(this.keptLength, n);\n const want = Math.min(len, n);\n if (want < kept) for (let k = n - kept; k < n - want; k++) addExact(p, -values[k]!);\n else for (let k = n - kept - 1; k >= n - want; k--) addExact(p, values[k]!);\n if (this.resizedSinceCommit++ > 0) this.resizedByLength.set(len, p.slice());\n return p;\n }\n\n /**\n * The sum of the last `length` values with the (not na) value `x` added, from the kept state; the state is\n * unchanged until {@link commit}.\n *\n * @returns The sum, or NaN while fewer than `length` values exist (with `x`)\n */\n step(x: number, length: number): number {\n const n = this.values.length;\n const p = this.resized(length - 1);\n addExact(p, x);\n this.stepPartials = p;\n this.stepLength = Math.min(length, n + 1);\n this.stepX = x;\n return n + 1 >= length ? roundExact(p) : NaN;\n }\n\n /**\n * The sum of the last `length` values on a bar with an na value (no value added), from the kept state; the state is\n * unchanged until {@link commit}. With an unchanged length, it is the previous result.\n *\n * @returns The sum, or NaN while fewer than `length` values exist\n */\n stepNa(length: number): number {\n const n = this.values.length;\n const p = this.resized(length);\n this.stepPartials = p;\n this.stepLength = Math.min(length, n);\n this.stepX = NaN;\n return n > 0 && n >= length ? roundExact(p) : NaN;\n }\n\n /** Keeps the state of the last {@link step} or {@link stepNa}. */\n commit(): void {\n if (!Number.isNaN(this.stepX)) this.values.push(this.stepX);\n this.keptLength = this.stepLength;\n this.partials = this.stepPartials;\n this.resizedSinceCommit = 0;\n if (this.resizedByLength.size > 0) this.resizedByLength.clear();\n }\n}\n\n/** The running sums of `source` with the length `lengthAt(i)` on bar `i`. */\nfunction sumWindows(source: ArrayLike<number | null | undefined>, lengthAt: (i: number) => number): number[] {\n const out: number[] = new Array<number>(source.length);\n const sum = new RunningSum();\n for (let i = 0; i < source.length; i++) {\n const v = source[i];\n const len = lengthAt(i);\n out[i] = isNa(v) ? sum.stepNa(len) : sum.step(v as number, len);\n sum.commit();\n }\n return out;\n}\n\n/**\n * The sum of the last `length` non-na values on each bar, correctly rounded, as PineScript.\n *\n * @param source - Values (na: NaN, null, undefined or +/-Infinity, skipped)\n * @param length - Number of non-na values in the window\n * @returns The running sum per bar: NaN until `length` non-na values exist; a bar with an na value keeps the\n * previous result\n */\nexport function runningSum(source: ArrayLike<number | null | undefined>, length: number): number[] {\n const len = Math.floor(length);\n if (!(len >= 1)) return new Array<number>(source.length).fill(NaN);\n return sumWindows(source, () => len);\n}\n\n/** The values of a series length, floored, checked to be at least 1 on every bar. */\nfunction seriesLengths(lengths: ArrayLike<number>, count: number, name: string): number[] {\n if (lengths.length < count) {\n throw new Error(`${name}: the length series has ${lengths.length} values for ${count} bars`);\n }\n return Array.from({ length: count }, (_, i) => {\n const len = Math.floor(lengths[i]!);\n checkSumLength(name, len, i);\n if (!(len >= 1)) throw new Error(`${name}: length must be at least 1 (bar ${i}: ${lengths[i]})`);\n return len;\n });\n}\n\n/**\n * The sum of the last `lengths[i]` non-na values on each bar `i` (a series length), as PineScript computes it (see\n * {@link RunningSum}). A bar with an na value gives the sum of the last `lengths[i]` earlier values.\n *\n * @param name - Function name for the error messages\n */\nexport function runningSumSeries(\n source: ArrayLike<number | null | undefined>,\n lengths: ArrayLike<number>,\n name = 'math.sum'\n): number[] {\n const lens = seriesLengths(lengths, source.length, name);\n return sumWindows(source, (i) => lens[i]!);\n}\n\n/** Variance from the window sums of the values and of their squares; rules in {@link runningVariance}. */\nfunction varianceFromSums(\n source: ArrayLike<number | null | undefined>,\n sumOf: (src: ArrayLike<number | null | undefined>) => number[],\n lengthAt: (i: number) => number,\n biased: boolean\n): number[] {\n const squares = Array.from({ length: source.length }, (_, i) => {\n const v = source[i];\n return isNa(v) ? NaN : (v as number) * (v as number);\n });\n const sums = sumOf(source);\n const sumSquares = sumOf(squares);\n return sums.map((sum, i) => {\n const len = lengthAt(i);\n const mean = sum / len;\n const sq = sumSquares[i]!;\n return biased ? sq / len - mean * mean : sq / (len - 1) - (mean * sum) / (len - 1);\n });\n}\n\n/**\n * Window variance from the window sums of the values and of their squares, as PineScript computes it (#188):\n * biased `sumSq / n - mean * mean`, unbiased `sumSq / (n - 1) - mean * sum / (n - 1)`, with `mean = sum / n`.\n */\nexport function runningVariance(\n source: ArrayLike<number | null | undefined>,\n length: number,\n biased: boolean\n): number[] {\n const len = Math.floor(length);\n return varianceFromSums(source, (src) => runningSum(src, len), () => len, biased);\n}\n\n/** {@link runningVariance} with a series length (the length of bar `i` is `lengths[i]`). */\nexport function runningVarianceSeries(\n source: ArrayLike<number | null | undefined>,\n lengths: ArrayLike<number>,\n biased: boolean,\n name = 'ta.variance'\n): number[] {\n const lens = seriesLengths(lengths, source.length, name);\n return varianceFromSums(source, (src) => sumWindows(src, (i) => lens[i]!), (i) => lens[i]!, biased);\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,oBAA+B;AAGxB,SAAS,KAAK,GAAuC;AAC1D,SAAO,MAAM,UAAa,MAAM,QAAQ,CAAC,OAAO,SAAS,CAAC;AAC5D;AAGA,SAAS,SAAS,GAAa,GAAiB;AAC9C,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;AACjC,QAAI,IAAI,EAAE,CAAC;AACX,QAAI,KAAK,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,
|
|
4
|
+
"sourcesContent": ["/**\n * Window sums of PineScript `math.sum` / `ta.sma` / `ta.stdev` / `ta.variance` / `ta.mfi` (bit for bit).\n *\n * PineScript gives the correctly rounded sum of the window values (the exact sum of the doubles, rounded once), on\n * every bar: `ta.sma` is that sum divided by the length (measured on the reference 05/11/2026, #188: built-in and\n * expression sources, with or without a `ta.stdev` of the same source, constant and series lengths, na values; 0\n * differing bars of 16,550 on BTCUSD 1D and 34,665 on AAPL 1D). The running sum of earlier versions (Kahan steps,\n * #114) gave a small residue on a window of zeros; the reference no longer does.\n *\n * The exact sum is kept as non-overlapping partials (Shewchuk's algorithm, as Python `math.fsum`): adding a value and\n * removing the one that leaves the window (adding its negation) are exact, so a bar costs the values that enter and\n * leave, not the whole window.\n *\n * @internal\n */\nimport { checkSumLength } from './limits.js';\n\n/** A value PineScript treats as na in window functions (also +/-Infinity). */\nexport function isNa(v: number | null | undefined): boolean {\n return v === undefined || v === null || !Number.isFinite(v);\n}\n\n/** Adds `x` to the partials `p` (non-overlapping, increasing magnitude), exactly. */\nfunction addExact(p: number[], x: number): void {\n let i = 0;\n for (let j = 0; j < p.length; j++) {\n let y = p[j]!;\n if (Math.abs(x) < Math.abs(y)) {\n const t = x;\n x = y;\n y = t;\n }\n const hi = x + y;\n const lo = y - (hi - x);\n if (lo !== 0) p[i++] = lo;\n x = hi;\n }\n p.length = i;\n p.push(x);\n}\n\n/** The partials' exact sum rounded once to a double (round half to even), as Python `math.fsum`. */\nfunction roundExact(p: readonly number[]): number {\n let n = p.length;\n if (n === 0) return 0;\n let hi = p[--n]!;\n while (n > 0) {\n const x = hi;\n const y = p[--n]!;\n hi = x + y;\n const lo = y - (hi - x);\n if (lo !== 0) {\n // half-way case: the rest has the same sign, so round away from the tie\n if (n > 0 && ((lo < 0 && p[n - 1]! < 0) || (lo > 0 && p[n - 1]! > 0))) {\n const y2 = lo * 2;\n const x2 = hi + y2;\n if (y2 === x2 - hi) hi = x2;\n }\n break;\n }\n }\n return hi;\n}\n\n/**\n * Window sum state, one value at a time. {@link step} computes the sum with a new value from the kept state without\n * changing it; {@link commit} keeps the last step. So several candidate values can be tried on one bar and only the\n * last one kept (a ta.* call in a loop).\n *\n * The length can change from one step to the next (a series length): the window is then the last `length` values,\n * the values that leave or come back are removed or added exactly.\n */\nexport class RunningSum {\n private readonly values: number[] = [];\n /** Exact sum of the kept window (the last `keptLength` values). */\n private partials: number[] = [];\n private keptLength = 0;\n private stepLength = 0;\n private stepX = NaN;\n private stepPartials: number[] = [];\n /**\n * {@link resized} partials of the kept state by length, until the next {@link commit}: the calls of a loop (several\n * steps on one bar) move the same kept sum to the same lengths. Kept from the second step on, so that one step per\n * bar costs nothing more.\n */\n private readonly resizedByLength = new Map<number, readonly number[]>();\n private resizedSinceCommit = 0;\n\n /** The partials of the last `len` values (kept state, nothing added); a new array. */\n private resized(len: number): number[] {\n const cached = this.resizedByLength.get(len);\n if (cached) return cached.slice();\n const values = this.values;\n const n = values.length;\n const p = this.partials.slice();\n const kept = Math.min(this.keptLength, n);\n const want = Math.min(len, n);\n if (want < kept) for (let k = n - kept; k < n - want; k++) addExact(p, -values[k]!);\n else for (let k = n - kept - 1; k >= n - want; k--) addExact(p, values[k]!);\n if (this.resizedSinceCommit++ > 0) this.resizedByLength.set(len, p.slice());\n return p;\n }\n\n /**\n * The sum of the last `length` values with the (not na) value `x` added, from the kept state; the state is\n * unchanged until {@link commit}.\n *\n * @returns The sum, or NaN while fewer than `length` values exist (with `x`)\n */\n step(x: number, length: number): number {\n const n = this.values.length;\n const p = this.resized(length - 1);\n addExact(p, x);\n this.stepPartials = p;\n this.stepLength = Math.min(length, n + 1);\n this.stepX = x;\n return n + 1 >= length ? roundExact(p) : NaN;\n }\n\n /**\n * The sum of the last `length` values on a bar with an na value (no value added), from the kept state; the state is\n * unchanged until {@link commit}. With an unchanged length, it is the previous result.\n *\n * @returns The sum, or NaN while fewer than `length` values exist\n */\n stepNa(length: number): number {\n const n = this.values.length;\n const p = this.resized(length);\n this.stepPartials = p;\n this.stepLength = Math.min(length, n);\n this.stepX = NaN;\n return n > 0 && n >= length ? roundExact(p) : NaN;\n }\n\n /** Keeps the state of the last {@link step} or {@link stepNa}. */\n commit(): void {\n if (!Number.isNaN(this.stepX)) this.values.push(this.stepX);\n this.keptLength = this.stepLength;\n this.partials = this.stepPartials;\n this.resizedSinceCommit = 0;\n if (this.resizedByLength.size > 0) this.resizedByLength.clear();\n }\n}\n\n/** The running sums of `source` with the length `lengthAt(i)` on bar `i`. */\nfunction sumWindows(source: ArrayLike<number | null | undefined>, lengthAt: (i: number) => number): number[] {\n const out: number[] = new Array<number>(source.length);\n const sum = new RunningSum();\n for (let i = 0; i < source.length; i++) {\n const v = source[i];\n const len = lengthAt(i);\n out[i] = isNa(v) ? sum.stepNa(len) : sum.step(v as number, len);\n sum.commit();\n }\n return out;\n}\n\n/**\n * The sum of the last `length` non-na values on each bar, correctly rounded, as PineScript.\n *\n * @param source - Values (na: NaN, null, undefined or +/-Infinity, skipped)\n * @param length - Number of non-na values in the window\n * @returns The running sum per bar: NaN until `length` non-na values exist; a bar with an na value keeps the\n * previous result\n */\nexport function runningSum(source: ArrayLike<number | null | undefined>, length: number): number[] {\n const len = Math.floor(length);\n const n = source.length;\n const out = new Array<number>(n);\n if (!(len >= 1)) return out.fill(NaN);\n // A constant length: the partials of the window are changed in place, with the steps of RunningSum in the same\n // order (the value that leaves, then the one that enters), so the sums are the same doubles without a copy per bar.\n const values: number[] = [];\n const p = new FixedPartials();\n let last = NaN;\n for (let i = 0; i < n; i++) {\n const v = source[i];\n if (!isNa(v)) {\n const count = values.length;\n if (count >= len) p.add(-values[count - len]!);\n p.add(v as number);\n values.push(v as number);\n last = count + 1 >= len ? p.round() : NaN;\n }\n out[i] = last;\n }\n return out;\n}\n\n/** The partials of {@link addExact} / {@link roundExact} in a typed array with a count (same operations). */\nclass FixedPartials {\n private p = new Float64Array(64);\n private n = 0;\n\n add(x: number): void {\n const p = this.p;\n const n = this.n;\n let i = 0;\n for (let j = 0; j < n; j++) {\n let y = p[j]!;\n if (Math.abs(x) < Math.abs(y)) {\n const t = x;\n x = y;\n y = t;\n }\n const hi = x + y;\n const lo = y - (hi - x);\n if (lo !== 0) p[i++] = lo;\n x = hi;\n }\n if (i === p.length) {\n const grown = new Float64Array(p.length * 2);\n grown.set(p);\n this.p = grown;\n }\n this.p[i] = x;\n this.n = i + 1;\n }\n\n round(): number {\n const p = this.p;\n let n = this.n;\n if (n === 0) return 0;\n let hi = p[--n]!;\n while (n > 0) {\n const x = hi;\n const y = p[--n]!;\n hi = x + y;\n const lo = y - (hi - x);\n if (lo !== 0) {\n if (n > 0 && ((lo < 0 && p[n - 1]! < 0) || (lo > 0 && p[n - 1]! > 0))) {\n const y2 = lo * 2;\n const x2 = hi + y2;\n if (y2 === x2 - hi) hi = x2;\n }\n break;\n }\n }\n return hi;\n }\n}\n\n/** The values of a series length, floored, checked to be at least 1 on every bar. */\nfunction seriesLengths(lengths: ArrayLike<number>, count: number, name: string): number[] {\n if (lengths.length < count) {\n throw new Error(`${name}: the length series has ${lengths.length} values for ${count} bars`);\n }\n return Array.from({ length: count }, (_, i) => {\n const len = Math.floor(lengths[i]!);\n checkSumLength(name, len, i);\n if (!(len >= 1)) throw new Error(`${name}: length must be at least 1 (bar ${i}: ${lengths[i]})`);\n return len;\n });\n}\n\n/**\n * The sum of the last `lengths[i]` non-na values on each bar `i` (a series length), as PineScript computes it (see\n * {@link RunningSum}). A bar with an na value gives the sum of the last `lengths[i]` earlier values.\n *\n * @param name - Function name for the error messages\n */\nexport function runningSumSeries(\n source: ArrayLike<number | null | undefined>,\n lengths: ArrayLike<number>,\n name = 'math.sum'\n): number[] {\n const lens = seriesLengths(lengths, source.length, name);\n return sumWindows(source, (i) => lens[i]!);\n}\n\n/** Variance from the window sums of the values and of their squares; rules in {@link runningVariance}. */\nfunction varianceFromSums(\n source: ArrayLike<number | null | undefined>,\n sumOf: (src: ArrayLike<number | null | undefined>) => number[],\n lengthAt: (i: number) => number,\n biased: boolean\n): number[] {\n const squares = Array.from({ length: source.length }, (_, i) => {\n const v = source[i];\n return isNa(v) ? NaN : (v as number) * (v as number);\n });\n const sums = sumOf(source);\n const sumSquares = sumOf(squares);\n return sums.map((sum, i) => {\n const len = lengthAt(i);\n const mean = sum / len;\n const sq = sumSquares[i]!;\n return biased ? sq / len - mean * mean : sq / (len - 1) - (mean * sum) / (len - 1);\n });\n}\n\n/**\n * Window variance from the window sums of the values and of their squares, as PineScript computes it (#188):\n * biased `sumSq / n - mean * mean`, unbiased `sumSq / (n - 1) - mean * sum / (n - 1)`, with `mean = sum / n`.\n */\nexport function runningVariance(\n source: ArrayLike<number | null | undefined>,\n length: number,\n biased: boolean\n): number[] {\n const len = Math.floor(length);\n return varianceFromSums(source, (src) => runningSum(src, len), () => len, biased);\n}\n\n/** {@link runningVariance} with a series length (the length of bar `i` is `lengths[i]`). */\nexport function runningVarianceSeries(\n source: ArrayLike<number | null | undefined>,\n lengths: ArrayLike<number>,\n biased: boolean,\n name = 'ta.variance'\n): number[] {\n const lens = seriesLengths(lengths, source.length, name);\n return varianceFromSums(source, (src) => sumWindows(src, (i) => lens[i]!), (i) => lens[i]!, biased);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,oBAA+B;AAGxB,SAAS,KAAK,GAAuC;AAC1D,SAAO,MAAM,UAAa,MAAM,QAAQ,CAAC,OAAO,SAAS,CAAC;AAC5D;AAGA,SAAS,SAAS,GAAa,GAAiB;AAC9C,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;AACjC,QAAI,IAAI,EAAE,CAAC;AACX,QAAI,KAAK,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,GAAG;AAC7B,YAAM,IAAI;AACV,UAAI;AACJ,UAAI;AAAA,IACN;AACA,UAAM,KAAK,IAAI;AACf,UAAM,KAAK,KAAK,KAAK;AACrB,QAAI,OAAO,EAAG,GAAE,GAAG,IAAI;AACvB,QAAI;AAAA,EACN;AACA,IAAE,SAAS;AACX,IAAE,KAAK,CAAC;AACV;AAGA,SAAS,WAAW,GAA8B;AAChD,MAAI,IAAI,EAAE;AACV,MAAI,MAAM,EAAG,QAAO;AACpB,MAAI,KAAK,EAAE,EAAE,CAAC;AACd,SAAO,IAAI,GAAG;AACZ,UAAM,IAAI;AACV,UAAM,IAAI,EAAE,EAAE,CAAC;AACf,SAAK,IAAI;AACT,UAAM,KAAK,KAAK,KAAK;AACrB,QAAI,OAAO,GAAG;AAEZ,UAAI,IAAI,MAAO,KAAK,KAAK,EAAE,IAAI,CAAC,IAAK,KAAO,KAAK,KAAK,EAAE,IAAI,CAAC,IAAK,IAAK;AACrE,cAAM,KAAK,KAAK;AAChB,cAAM,KAAK,KAAK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