Skip to content

πŸ“ˆ Get real-time stocks from TradingView

Handle malformed strategy reports atomically and document Basic exports (#332)

Mathieu Colmon6c8390b55ba5
diff --git a/docs/data-api.md b/docs/data-api.md
index de176b2..710f73d 100644
--- a/docs/data-api.md
+++ b/docs/data-api.md
@@ -174,9 +174,20 @@ Raw percentage/fraction fields are not rescaled. History series, including buy &
hold, are retained independently even when no equity series is provided. Updates
replace supplied arrays and retain omitted series; an empty array clears a series.
+Malformed trade lists (a non-array or non-object records) raise `PARSE_ERROR`
+before any part of that report is applied. Studies emit this error for both plain
+and compressed reports. Omitted trade lists retain previous records; `[]` clears them.
+This is structural validation, not full validation of every trade field.
+
These offline checks validate report decoding and normalization, not fresh-client
access, Replay playback, export entitlement or Deep Backtesting availability.
+In a Basic-account UI check on October 3, 2026, both strategy trade CSV export and
+strategy report XLSX export opened an upgrade prompt recommending Essential.
+No successful export was verified. These are TradingView UI entitlements, not
+library export methods or a guarantee about other accounts. Deep Backtesting is
+separate and was blocked by a Premium upgrade prompt in that session.
+
## Search and technical analysis
```ts
diff --git a/src/chart/strategy.ts b/src/chart/strategy.ts
index 917c0c9..d722e1a 100644
--- a/src/chart/strategy.ts
+++ b/src/chart/strategy.ts
@@ -1,3 +1,5 @@
+import { TradingViewError } from '../errors.js';
+
/** A value with absolute and percent forms. */
export interface RelAbsValue {
v: number;
@@ -88,6 +90,10 @@ export type StrategyReportChange =
/** Converts raw trades (oldest first) into readable trades (most recent first). */
export function parseTrades(trades: any[]): TradeReport[] {
+ if (!Array.isArray(trades) || trades.some((trade) =>
+ !trade || typeof trade !== 'object' || Array.isArray(trade))) {
+ throw new TradingViewError('PARSE_ERROR', 'Strategy trades must be an array of records');
+ }
return [...trades].reverse().map((t) => ({
entry: {
name: t.e?.c,
@@ -109,6 +115,9 @@ export function mergeStrategyReport(target: StrategyReport, report: any): Strate
const changes: StrategyReportChange[] = [];
if (!report || typeof report !== 'object') return changes;
+ // Parse before mutating the target so a malformed trade list cannot leave a partial merge.
+ const trades = report.trades === undefined ? undefined : parseTrades(report.trades);
+
if (report.currency) {
target.currency = report.currency;
changes.push('report.currency');
@@ -121,8 +130,8 @@ export function mergeStrategyReport(target: StrategyReport, report: any): Strate
target.performance = report.performance;
changes.push('report.perf');
}
- if (report.trades) {
- target.trades = parseTrades(report.trades);
+ if (trades !== undefined) {
+ target.trades = trades;
changes.push('report.trades');
}
const historyKeys = [
diff --git a/src/chart/study.ts b/src/chart/study.ts
index af8617f..9db3ffd 100644
--- a/src/chart/study.ts
+++ b/src/chart/study.ts
@@ -217,7 +217,15 @@ export class Study extends Emitter<StudyEvents> {
}
}
- if (parsed?.data?.report) changes.push(...mergeStrategyReport(this.#strategyReport, parsed.data.report));
+ if (parsed?.data?.report) {
+ try {
+ changes.push(...mergeStrategyReport(this.#strategyReport, parsed.data.report));
+ } catch (error) {
+ this.emit('error', new TradingViewError('PARSE_ERROR', 'Unable to parse strategy report', {
+ cause: error,
+ }));
+ }
+ }
}
if (Array.isArray(ns?.indexes)) this.#graphicIndexes = ns.indexes;
diff --git a/tests/unit/strategy.test.ts b/tests/unit/strategy.test.ts
index 0be2d95..5f88e25 100644
--- a/tests/unit/strategy.test.ts
+++ b/tests/unit/strategy.test.ts
@@ -55,4 +55,28 @@ describe('strategy report normalization', () => {
mergeStrategyReport(report, { performance: { all: { netProfit: Infinity }, openPL: NaN } });
expect(summarizeStrategyReport(report)).toMatchObject({ closedNetProfit: undefined, openPnL: undefined, totalPnL: undefined });
});
+ it('rejects malformed trade lists without partially overwriting the report', () => {
+ const report = empty();
+ mergeStrategyReport(report, { currency: 'USD', performance: { openPL: 2 }, equity: [100] });
+ const before = structuredClone(report);
+ for (const trades of [null, {}, 'invalid', [null], [1], [[]]]) {
+ expect(() => mergeStrategyReport(report, {
+ currency: 'EUR', performance: { openPL: 9 }, trades, equity: [200],
+ })).toThrow('Strategy trades must be an array of records');
+ expect(report).toEqual(before);
+ }
+ expect(mergeStrategyReport(report, { trades: [] })).toEqual(['report.trades']);
+ expect(report.trades).toEqual([]);
+ });
+
+ it('keeps missing PnL unknown and rejects an overflowing total', () => {
+ const report = empty();
+ mergeStrategyReport(report, { performance: { all: { totalOpenTrades: 0, netProfit: 2 } } });
+ expect(summarizeStrategyReport(report).totalPnL).toBeUndefined();
+ mergeStrategyReport(report, {
+ performance: { all: { netProfit: Number.MAX_VALUE }, openPL: Number.MAX_VALUE },
+ });
+ expect(summarizeStrategyReport(report).totalPnL).toBeUndefined();
+ });
+
});
diff --git a/tests/unit/study.test.ts b/tests/unit/study.test.ts
index 4baaace..58e3966 100644
--- a/tests/unit/study.test.ts
+++ b/tests/unit/study.test.ts
@@ -167,4 +167,26 @@ describe('Study', () => {
expect(error.code).toBe('PARSE_ERROR');
await client.close();
});
+ it('emits PARSE_ERROR for malformed plain and compressed trades without mutating the report', async () => {
+ const payload = { report: { currency: 'EUR', trades: [null] } };
+ for (const ns of [
+ { data: payload },
+ { dataCompressed: deflateSync(JSON.stringify(payload)).toString('base64') },
+ ]) {
+ const { client, chart } = await setup({ studyNs: () => ns });
+ try {
+ const study = chart.createStudy(makePine());
+ const errors: any[] = [];
+ study.on('error', (error) => errors.push(error));
+ await until(() => study.isReady);
+ expect(errors).toHaveLength(1);
+ expect(errors[0].code).toBe('PARSE_ERROR');
+ expect(study.strategyReport.currency).toBeUndefined();
+ expect(study.strategyReport.trades).toEqual([]);
+ } finally {
+ await client.close();
+ }
+ }
+ });
+
});