π Get real-time stocks from TradingView
TypeScript backtestingbacktesting-trading-strategiesbitcoinchartscryptocryptocurrencyethereumrealtime-stocksstocksstocks-apistocks-pricestradingtradingviewtradingview-apitradingview-indicatortradingview-replaytradingview-scraper
Preserve strategy history and distinguish open/closed totals (#331)
Mathieu Colmon1ec410f8bfab
diff --git a/docs/data-api.md b/docs/data-api.mdindex b535161..de176b2 100644--- a/docs/data-api.md+++ b/docs/data-api.md@@ -152,6 +152,31 @@ Without an account, TradingView refuses Pine studies ("maximum number of studies`watchIndicator(query, { onData, onError })` streams the same result on every study update; `watcher.latest` holds the last one.+### Strategy totals and open positions++```ts+import { summarizeStrategyReport } from '@mathieuc/tradingview/data';++const summary = summarizeStrategyReport(result.strategyReport);+// tradeRecordCount, closedTradeCount, openTradeCount,+// closedNetProfit, openPnL, totalPnL, currency+```++Trade records can include open positions with a current exit valuation. An `exit`+object does **not** establish that a trade is closed. The summary uses reported+`performance.all.totalTrades` and `totalOpenTrades`, never the record count, for+closed/open counts. It does not assign a closed/open status to individual records.+Counts may differ from the available records in a partial report.++`totalPnL` is closed net profit plus open PnL, in the report currency. Missing or+non-finite values remain `undefined`; a missing open PnL is not assumed to be zero.+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.++These offline checks validate report decoding and normalization, not fresh-client+access, Replay playback, export entitlement or Deep Backtesting availability.+## Search and technical analysis```tsdiff --git a/src/chart/index.ts b/src/chart/index.tsindex b8c58ad..4a82791 100644--- a/src/chart/index.ts+++ b/src/chart/index.ts@@ -12,9 +12,9 @@ export type {GraphicPoint, GraphicPolygon, GraphicTable, GraphicsData, HAlignValue, LabelStyleValue, LineStyleValue,RawGraphics, SizeValue, TableCell, TablePositionValue, TextWrapValue, VAlignValue, YLocValue,} from './graphics.js';-export { mergeStrategyReport, parseTrades } from './strategy.js';+export { mergeStrategyReport, parseTrades, summarizeStrategyReport } from './strategy.js';export type {- FromTo, PerformanceReport, RelAbsValue, StrategyReport, StrategyReportChange, TradeReport,+ FromTo, PerformanceReport, RelAbsValue, StrategyReport, StrategyReportChange, StrategySummary, TradeReport,} from './strategy.js';export { timeframeSeconds } from './timeframes.js';export { CHART_TYPE_STUDIES } from './types.js';diff --git a/src/chart/strategy.ts b/src/chart/strategy.tsindex c2a81d7..917c0c9 100644--- a/src/chart/strategy.ts+++ b/src/chart/strategy.ts@@ -57,7 +57,7 @@ export interface FromTo {export interface StrategyReport {currency?: string;settings?: { dateRange?: { backtest?: FromTo; trade?: FromTo }; [key: string]: unknown };- /** Trades, most recent first. */+ /** Trade records, most recent first; may include open positions with an exit valuation. */trades: TradeReport[];history: {buyHold?: number[];@@ -125,16 +125,50 @@ export function mergeStrategyReport(target: StrategyReport, report: any): Stratetarget.trades = parseTrades(report.trades);changes.push('report.trades');}- if (report.equity) {- target.history = {- buyHold: report.buyHold,- buyHoldPercent: report.buyHoldPercent,- drawDown: report.drawDown,- drawDownPercent: report.drawDownPercent,- equity: report.equity,- equityPercent: report.equityPercent,- };- changes.push('report.history');+ const historyKeys = [+ 'buyHold', 'buyHoldPercent', 'drawDown', 'drawDownPercent', 'equity', 'equityPercent',+ ] as const;+ let historyChanged = false;+ for (const key of historyKeys) {+ if (Array.isArray(report[key])) {+ target.history[key] = report[key];+ historyChanged = true;+ }}+ if (historyChanged) changes.push('report.history');return changes;}++/** Aggregate counts are authoritative; an exit valuation does not prove closure. */+export interface StrategySummary {+ tradeRecordCount: number;+ closedTradeCount?: number;+ openTradeCount?: number;+ closedNetProfit?: number;+ openPnL?: number;+ /** Available only when both closed and open PnL are present. */+ totalPnL?: number;+ currency?: string;+}++/** Summarizes reported aggregates without inferring missing values or trade status. */+export function summarizeStrategyReport(report: StrategyReport): StrategySummary {+ const finite = (value: unknown): number | undefined =>+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;+ const count = (value: unknown): number | undefined => {+ const n = finite(value);+ return n !== undefined && Number.isInteger(n) && n >= 0 ? n : undefined;+ };+ const closedNetProfit = finite(report.performance.all?.netProfit);+ const openPnL = finite(report.performance.openPL);+ return {+ currency: report.currency,+ tradeRecordCount: report.trades.length,+ closedTradeCount: count(report.performance.all?.totalTrades),+ openTradeCount: count(report.performance.all?.totalOpenTrades),+ closedNetProfit,+ openPnL,+ totalPnL: closedNetProfit !== undefined && openPnL !== undefined+ ? finite(closedNetProfit + openPnL) : undefined,+ };+}diff --git a/src/data/index.ts b/src/data/index.tsindex d381f95..6712f56 100644--- a/src/data/index.ts+++ b/src/data/index.ts@@ -43,3 +43,6 @@ export type { QuoteData, QuoteField } from '../quote/fields.js';export type { StudyValue } from '../chart/study.js';export type { GraphicsData } from '../chart/graphics.js';export type { StrategyReport } from '../chart/strategy.js';++export { summarizeStrategyReport } from '../chart/strategy.js';+export type { StrategySummary } from '../chart/strategy.js';diff --git a/tests/unit/exports.test.ts b/tests/unit/exports.test.tsindex eaebc7b..5872e52 100644--- a/tests/unit/exports.test.ts+++ b/tests/unit/exports.test.ts@@ -10,7 +10,7 @@ describe('public API', () => {'TradingViewError', 'TradingViewProvider', 'applyGraphicsCommands', 'clearIndicatorCache', 'getCandles', 'getChartToken', 'getDrawings','getIndicator', 'getIndicatorData', 'getPrivateIndicators', 'getQuote', 'getQuotes', 'getSymbolInfo','getTechnicalAnalysis', 'getUser', 'loginUser', 'mergeStrategyReport', 'parseGraphics', 'parseIndicatorDefinition',- 'parseTrades', 'protocol', 'quoteSymbolKey', 'resolveQuoteFields', 'searchIndicators', 'searchMarkets',+ 'parseTrades', 'protocol', 'quoteSymbolKey', 'resolveQuoteFields', 'searchIndicators', 'searchMarkets', 'summarizeStrategyReport','timeframeSeconds', 'toTradingViewError', 'watchCandles', 'watchIndicator', 'watchQuotes', 'wsTransport',]);expect(Object.keys(root.protocol).sort()).toEqual([@@ -22,7 +22,7 @@ describe('public API', () => {it('data entry only exposes the simplified data API', () => {expect(Object.keys(data).sort()).toEqual(['DEFAULT_TIMEOUT_MS', 'TradingViewError', 'TradingViewProvider', 'getCandles', 'getIndicatorData', 'getQuote', 'getQuotes', 'getSymbolInfo',- 'getTechnicalAnalysis', 'searchIndicators', 'searchMarkets', 'watchCandles', 'watchIndicator', 'watchQuotes',+ 'getTechnicalAnalysis', 'searchIndicators', 'searchMarkets', 'summarizeStrategyReport', 'watchCandles', 'watchIndicator', 'watchQuotes',]);expect(data.getCandles).toBe(root.getCandles);});diff --git a/tests/unit/strategy.test.ts b/tests/unit/strategy.test.tsnew file mode 100644index 0000000..0be2d95--- /dev/null+++ b/tests/unit/strategy.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest';+import { mergeStrategyReport, summarizeStrategyReport, type StrategyReport } from '../../src/chart/strategy.js';++const empty = (): StrategyReport => ({ trades: [], history: {}, performance: {} });++describe('strategy report normalization', () => {+ it('keeps buy-and-hold history without equity and preserves omitted series on updates', () => {+ const report = empty();+ expect(mergeStrategyReport(report, { buyHold: [1, 2], buyHoldPercent: [0, 0.1] }))+ .toEqual(['report.history']);+ mergeStrategyReport(report, { equity: [10, 11] });+ mergeStrategyReport(report, { buyHold: [] });+ expect(report.history).toEqual({ buyHold: [], buyHoldPercent: [0, 0.1], equity: [10, 11] });+ expect(mergeStrategyReport(report, { equity: null, buyHold: 'invalid' })).toEqual([]);+ expect(report.history.equity).toEqual([10, 11]);+ });++ it('uses aggregate counts even when every trade record has an exit valuation', () => {+ const report = empty();+ // Synthetic data reproduces the observed shape, not private strategy results.+ mergeStrategyReport(report, {+ currency: 'USD',+ performance: { all: { totalTrades: 2, totalOpenTrades: 1, netProfit: 12 }, openPL: -3 },+ trades: Array.from({ length: 3 }, (_, i) => ({+ e: { c: 'Entry', tp: 'le', p: 100, tm: i * 1000 },+ x: { c: '', p: 97, tm: (i + 1) * 1000 }, q: 1,+ tp: { v: -3, p: -0.03 }, cp: { v: 9, p: 0.09 },+ rn: { v: 1, p: 0.01 }, dd: { v: 3, p: 0.03 },+ })),+ });+ const before = structuredClone(report);+ expect(summarizeStrategyReport(report)).toEqual({+ currency: 'USD', tradeRecordCount: 3, closedTradeCount: 2, openTradeCount: 1,+ closedNetProfit: 12, openPnL: -3, totalPnL: 9,+ });+ expect(report).toEqual(before);+ });++ it('does not invent zero counts or total PnL for missing or invalid aggregates', () => {+ const report = empty();+ expect(summarizeStrategyReport(report)).toMatchObject({+ tradeRecordCount: 0, closedTradeCount: undefined, openTradeCount: undefined,+ closedNetProfit: undefined, openPnL: undefined, totalPnL: undefined,+ });+ mergeStrategyReport(report, {+ performance: { all: { totalTrades: -1, totalOpenTrades: 0.5, netProfit: 12 } },+ });+ expect(summarizeStrategyReport(report)).toMatchObject({+ closedTradeCount: undefined, openTradeCount: undefined, closedNetProfit: 12, totalPnL: undefined,+ });+ mergeStrategyReport(report, {+ performance: { all: { totalTrades: 0, totalOpenTrades: 0, netProfit: 0 }, openPL: 0 },+ });+ expect(summarizeStrategyReport(report)).toMatchObject({ closedTradeCount: 0, openTradeCount: 0, totalPnL: 0 });+ mergeStrategyReport(report, { performance: { all: { netProfit: Infinity }, openPL: NaN } });+ expect(summarizeStrategyReport(report)).toMatchObject({ closedNetProfit: undefined, openPnL: undefined, totalPnL: undefined });+ });+});diff --git a/tests/unit/study.test.ts b/tests/unit/study.test.tsindex 3fdf754..4baaace 100644--- a/tests/unit/study.test.ts+++ b/tests/unit/study.test.ts@@ -1,4 +1,5 @@import { readFileSync } from 'node:fs';+import { deflateSync } from 'node:zlib';import { describe, expect, it } from 'vitest';import { TradingViewClient } from '../../src/client/client.js';import { applyGraphicsCommands, parseGraphics } from '../../src/chart/graphics.js';@@ -145,6 +146,20 @@ describe('Study', () => {}});+ it('decodes an unpadded zlib report with buy-and-hold history but no equity', async () => {+ const payload = { report: {+ currency: 'USD', buyHold: [100, 102], buyHoldPercent: [0, 0.02],+ performance: { all: { totalTrades: 2, totalOpenTrades: 1, netProfit: 12 }, openPL: -3 },+ } };+ const dataCompressed = deflateSync(JSON.stringify(payload)).toString('base64').replace(/=+$/, '');+ const { client, chart } = await setup({ studyNs: () => ({ dataCompressed }) });+ const study = chart.createStudy(makePine());+ await until(() => study.isReady);+ expect(study.strategyReport.history).toEqual({ buyHold: [100, 102], buyHoldPercent: [0, 0.02] });+ expect(study.strategyReport.performance).toEqual(payload.report.performance);+ await client.close();+ });+it('reports undecodable strategy reports as PARSE_ERROR', async () => {const { client, chart } = await setup({ studyNs: () => ({ dataCompressed: 'bm90IGpzb24' }) });const study = chart.createStudy(makePine());