π Get real-time stocks from TradingView
TypeScript backtestingbacktesting-trading-strategiesbitcoinchartscryptocryptocurrencyethereumrealtime-stocksstocksstocks-apistocks-pricestradingtradingviewtradingview-apitradingview-indicatortradingview-replaytradingview-scraper
Prepare beta.1 with strategy report example and Basic Replay validation (#333)
Mathieu Colmonda67081a9c36
diff --git a/docs/data-api.md b/docs/data-api.mdindex 710f73d..5d2e8c4 100644--- a/docs/data-api.md+++ b/docs/data-api.md@@ -188,6 +188,26 @@ No successful export was verified. These are TradingView UI entitlements, notlibrary export methods or a guarantee about other accounts. Deep Backtesting isseparate and was blocked by a Premium upgrade prompt in that session.+### Complete strategy report example++See [strategy-report.js](../examples/strategy-report.js) for a bounded, executable+public-strategy β trade-records β PnL-summary workflow. Run it from a repository+checkout after building:++```bash+node --env-file=.env examples/strategy-report.js+```++It uses the account cookies from `.env`, runs a public Supertrend strategy and+closes its connection automatically. It places no orders. Trade records are+most recent first and can include open positions with current exit valuations;+use the reported aggregate counts rather than inferring closure from an exit.+Missing summary fields remain `undefined`, not zero. `count` selects returned+candles, not a guaranteed exact strategy backtest window. Basic was sufficient+for the tested symbol/timeframe; UI exports and Deep Backtesting have separate+subscription requirements.++## Search and technical analysis```tsdiff --git a/docs/release-4.0.0-beta.1.md b/docs/release-4.0.0-beta.1.mdnew file mode 100644index 0000000..c3b2591--- /dev/null+++ b/docs/release-4.0.0-beta.1.md@@ -0,0 +1,39 @@+# 4.0.0-beta.1 release candidate++Status: prepared for review; not published by this change.+Target npm dist-tag: **beta**. Keep **latest** on 3.5.2.++## Changes since beta.0++- Preserve buy-and-hold history even when a report has no equity history (#331).+- Export `summarizeStrategyReport`: separate record counts, closed/open trade+ counts, closed net profit, open PnL and total PnL; retain unknown fields as+ undefined (#331).+- Reject structurally malformed trade lists before modifying a report; report+ parse errors consistently for plain and compressed envelopes (#332).+- Add a runnable public-strategy/report/PnL example, with bounded execution,+ credential checks and explicit failure status.+- Document Basic Replay playback evidence and separate paid UI export and+ Deep Backtesting limits from library report access.++## Validation++- Deterministic Node/Bun suites, typecheck, lint, build and packed-consumer smoke+ checks are required before publication.+- Basic live probe: daily BINANCE:BTCEUR Replay load, three step acknowledgments,+ automatic bar advancement, start and stop acknowledgments.+- Strategy example executed against Basic; report aggregates and history returned.+- Private compressed strategy capture validated in the preceding fixes.+- No claim of universal Replay entitlement, UI export success or Deep Backtesting.++## Publication gate++Publication requires the maintainer's explicit go-ahead. After approval, use the+reviewed commit with a clean checkout, rerun package checks, and publish the+inspected tarball using `npm publish <tarball> --tag beta`. Verify the resulting+version and dist-tags. Do not use the default `latest` tag. No tag, GitHub release,+or npm publication is created by preparing this candidate.++For v3 migration and breaking changes inherited from beta.0, see+[migration-v4.md](migration-v4.md). This candidate adds no new intended breaking+change relative to beta.0.diff --git a/docs/v4-coverage.md b/docs/v4-coverage.mdindex db34eb8..8660335 100644--- a/docs/v4-coverage.md+++ b/docs/v4-coverage.md@@ -6,7 +6,7 @@ This matrix lists every capability of v3 (`main.js`, `src/`, examples, tests) an**Evidence columns**-- **Unit**: deterministic test in `tests/unit/` (`npm test` with Vitest on Node, `npm run test:bun` with Bun's runner; 108 tests, both green). Websocket tests use a scripted fake server (`tests/helpers/fake-server.ts`) or packets captured from TradingView (`tests/fixtures/live-session.json`); HTTP tests use a mocked `fetch`.+- **Unit**: deterministic test in `tests/unit/` (`npm test` with Vitest on Node, `npm run test:bun` with Bun's runner; 115 tests, both green). Websocket tests use a scripted fake server (`tests/helpers/fake-server.ts`) or packets captured from TradingView (`tests/fixtures/live-session.json`); HTTP tests use a mocked `fetch`.- **Live**: result of `npm run test:live` (`tests/live/`) and examples against TradingView on **2 October 2026**: 16 anonymous tests locally and 21 tests (including five authenticated) in the [manual GitHub Actions run](https://github.com/Mathieu2301/TradingView-API/actions/runs/37075296707):- β verified live anonymously;- π path or variant not exercised live (often requires a specific account asset); deterministic tests only;@@ -31,7 +31,7 @@ Test names are abbreviated as `file βΊ test`.| --- | --- | --- | --- || `protocol.parseWSPacket` (frame split, heartbeat as number, invalid JSON warning) | `protocol.decodeFrames` (length-based, UTF-16 lengths, typed frames, lenient fallback, invalid frames reported) | `protocol βΊ decodes several frames...`, `keeps payloads containing frame markers intact`, `reports invalid JSON...`, `falls back to splitting malformed input`, `decodes every message of a captured live session` | β (fixture captured live; UTF-16 lengths checked on Japanese/Korean descriptions) || `protocol.formatWSPacket` | `protocol.encodeFrame`, `encodePacket`, `encodeHeartbeat` | `protocol βΊ encodes packets with UTF-16 lengths` | β |-| `protocol.parseCompressed` (ZIP via jszip, base64 normalisation, zlib/raw/gzip fallbacks) | `protocol.decodeCompressed` (built-in ZIP reader: stored, deflated, data descriptors, empty entry names; zlib, raw deflate, gzip, plain JSON) and `normaliseBase64`, `readFirstZipEntry` | `protocol βΊ compressed payloads βΊ *` (ZIP fixtures generated independently with Python `zipfile`) | π live compressed strategy payload not captured; plain report verified |+| `protocol.parseCompressed` (ZIP via jszip, base64 normalisation, zlib/raw/gzip fallbacks) | `protocol.decodeCompressed` (built-in ZIP reader: stored, deflated, data descriptors, empty entry names; zlib, raw deflate, gzip, plain JSON) and `normaliseBase64`, `readFirstZipEntry` | `protocol βΊ compressed payloads βΊ *` (ZIP fixtures generated independently with Python `zipfile`) | β private compressed browser capture replayed through compiled parser (3 October 2026); plain report verified || `utils.genSessionID` | `protocol.createSessionId` (crypto-random) | `protocol βΊ ids` | β || `utils.genAuthCookies` | Internal cookie builder used by every HTTP call | `http βΊ * with credentials` (cookie headers asserted) | β || Websocket URL `wss://<server>.tradingview.com/socket.io/websocket?from=chart&type=chart`, Origin and browser headers | Same, in `TradingViewClient`; transport is pluggable (`transport` option, default `ws`) | `client βΊ connects with browser-like headers...` | β Node and Bun (Bun needed the Origin header fix) |@@ -89,7 +89,7 @@ Test names are abbreviated as `file βΊ test`.| v3 capability | v4 | Unit evidence | Live || --- | --- | --- | --- || `setMarket(symbol, { replay })` (replay session, add series, reset) | Same option | `chart βΊ runs replay mode...` | β |-| `replayStep(n)`, `replayStart(interval)`, `replayStop()` resolved by `replay_ok` | Same; reject with `INVALID_STATE` outside replay and on delete | `chart βΊ runs replay mode...`, `rejects pending replay requests...` | β step (`sessions βΊ replays history step by step`); β start/stop live |+| `replayStep(n)`, `replayStart(interval)`, `replayStop()` resolved by `replay_ok` | Same; reject with `INVALID_STATE` outside replay and on delete | `chart βΊ runs replay mode...`, `rejects pending replay requests...` | β step (`sessions βΊ replays history step by step`); β start/stop acknowledgments and advancing bars on Basic (3 October 2026) || `onReplayLoaded`, `onReplayPoint`, `onReplayResolution`, `onReplayEnd` | `replayLoaded`, `replayPoint`, `replayResolution`, `replayEnd` events | `chart βΊ runs replay mode...` | β || Replay `critical_error` | `CRITICAL_ERROR` on the chart; pending replay requests rejected | (code path shared with chart errors) | β |@@ -102,7 +102,7 @@ Test names are abbreviated as `file βΊ test`.| `study.periods` with plot names, `plot_N` fallback for unnamed/duplicate plots | `study.values` (oldest first) | `study βΊ creates a Pine study, names plots...`, `chart βΊ parses a captured live chart session` | β (built-in volume rows) || `study.graphic` (labels, lines, boxes, tables + cells, polygons, horizLines, horizHists, raw) and `graphicsCmds` erase/create | `study.graphics` (`cells` array, `raw` object) | `study βΊ reads graphics commands...`, `applies erase commands` | β horizontal histograms (volume profile); π Pine drawings || Bars-back translation of graphic X indexes | Same | `study βΊ reads graphics commands...` | β |-| `study.strategyReport` (plain `data.report` and compressed `dataCompressed`; trades, performance, history, currency, settings) | Same | `study βΊ decodes plain and compressed strategy reports`, `reports undecodable strategy reports as PARSE_ERROR` | β Supertrend strategy report with account; compressed variant unit-tested |+| `study.strategyReport` (plain `data.report` and compressed `dataCompressed`; trades, performance, history, currency, settings) | Same | `study βΊ decodes plain and compressed strategy reports`, `reports undecodable strategy reports as PARSE_ERROR` | β Supertrend strategy report with account; compressed variant also validated using a private browser capture || `study.setIndicator()` (`modify_study`) | Same | `study βΊ modifies and removes a study` | π || `study.remove()` | Same (idempotent) | same | β || `onReady`, `onUpdate`, `onError`, `study_error` | `ready`, `loading`, `update`, `error` (`STUDY_ERROR`, message formatted with server context) | `study βΊ formats study errors with their context` | β (anonymous Pine refusal reported as `STUDY_ERROR`) |@@ -189,4 +189,25 @@ These v3 behaviours were changed on purpose; none removes a capability.## Not verified live for this release-The 21-test manual live workflow verified authenticated connection, account lookup, a public Pine RSI, a Supertrend strategy report, the private-indicators listing endpoint, and recent historical `to` with an account. It did **not** verify password login, actual private/invite-only scripts, compressed strategy reports against a live response, older history beyond server limits, second-based/custom timeframes, the `prodata` server, owned layouts/drawings, or Pine permission changes. Those paths have deterministic tests but need the corresponding account assets to verify live. Run `SESSION=... SIGNATURE=... npm run test:live` to repeat the authenticated subset.+The 21-test manual live workflow verified authenticated connection, account lookup, a public Pine RSI, a Supertrend strategy report, the private-indicators listing endpoint, and recent historical `to` with an account. It did **not** verify password login, actual private/invite-only scripts, older history beyond server limits, second-based/custom timeframes, the `prodata` server, owned layouts/drawings, or Pine permission changes. Those paths have deterministic tests but need the corresponding account assets to verify live. Run `SESSION=... SIGNATURE=... npm run test:live` to repeat the authenticated subset.++## Basic account follow-up β 3 October 2026++A fresh authenticated library client loaded `BINANCE:BTCEUR` daily Replay at a+reference 30 days before the probe. Loading returned five bars; three step+requests were acknowledged; automatic playback produced advancing bar timestamps;+start and stop were both acknowledged. The client was closed after the bounded+probe. This verifies the library protocol for that symbol/timeframe/reference,+not intraday Replay, every exchange, unlimited history, or simulated order entry.+The existing browser chart and its settings were not changed.++`examples/strategy-report.js` was executed with the same Basic account against+the public Supertrend strategy on `BINANCE:BTCEUR`, timeframe `60`, count `300`.+It returned trade records, closed/open aggregate counts and PnL, and buy-and-hold+history. No private payloads or credentials are included in this repository.+The strategy may compute over more history than the requested candle count;+`count` is not an exact backtest-window guarantee.++UI CSV and XLSX exports remain plan-blocked (Essential offered), and Deep+Backtesting remains plan-blocked (Premium offered). The library report example+is not an implementation of those UI exports and does not enable Deep Backtesting.diff --git a/eslint.config.js b/eslint.config.jsindex 1368c02..8e1612c 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -10,7 +10,7 @@ export default tseslint.config(languageOptions: {globals: {console: 'readonly', process: 'readonly', setTimeout: 'readonly', clearTimeout: 'readonly',- setInterval: 'readonly', clearInterval: 'readonly', AbortController: 'readonly', URL: 'readonly',+ setInterval: 'readonly', clearInterval: 'readonly', AbortController: 'readonly', AbortSignal: 'readonly', URL: 'readonly',},},rules: {diff --git a/examples/README.md b/examples/README.mdindex 2754f90..323d157 100644--- a/examples/README.md+++ b/examples/README.md@@ -24,6 +24,7 @@ Examples that need an account read the `SESSION` and `SIGNATURE` cookies from th| [quote-session.js](quote-session.js) | `QuoteSession` | No || [builtin-indicator.js](builtin-indicator.js) | `BuiltInIndicator`, study graphics | No || [fake-replay.js](fake-replay.js) | Negative counts and `fetchMore` | No |+| [strategy-report.js](strategy-report.js) | Public strategy β trade records β closed/open PnL summary | Yes (Basic tested) || [replay.js](replay.js) | Replay mode with studies | Pine studies only || [custom-timeframe.js](custom-timeframe.js) | Second-based timeframes | Yes || [from-to.js](from-to.js) | Reference times and ranges | Yes |diff --git a/examples/strategy-report.js b/examples/strategy-report.jsnew file mode 100644index 0000000..10d3970--- /dev/null+++ b/examples/strategy-report.js@@ -0,0 +1,30 @@+// Run: npm run build && node --env-file=.env examples/strategy-report.js+// Computes a public Pine strategy; does not place orders or export the TradingView UI.+import { getIndicatorData, summarizeStrategyReport } from '@mathieuc/tradingview';++if (!process.env.SESSION || !process.env.SIGNATURE) {+ console.error('Set SESSION and SIGNATURE in your environment (see .env.sample).');+ process.exitCode = 1;+} else {+ try {+ const { strategyReport } = await getIndicatorData({+ symbol: 'BINANCE:BTCEUR',+ timeframe: '60',+ count: 300,+ indicator: 'STD;Supertrend%Strategy',+ inputs: { commission_type: 'percent', default_qty_value: 20 },+ credentials: { session: process.env.SESSION, signature: process.env.SIGNATURE },+ timeoutMs: 30_000,+ signal: AbortSignal.timeout(45_000),+ });+ if (!strategyReport.performance.all) throw new Error('No strategy performance received');+ // Missing aggregates remain undefined, not zero. totalPnL requires both components.+ console.log('Summary:', summarizeStrategyReport(strategyReport));+ // Most recent first. An exit valuation alone does NOT prove that a trade is closed.+ console.log('Latest trade records:', strategyReport.trades.slice(0, 5));+ console.log('Available history:', Object.keys(strategyReport.history));+ } catch (error) {+ console.error(error.code ?? 'STRATEGY_ERROR', error.message);+ process.exitCode = 1;+ }+}diff --git a/package-lock.json b/package-lock.jsonindex ad65af0..c58644d 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "@mathieuc/tradingview",- "version": "4.0.0-beta.0",+ "version": "4.0.0-beta.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@mathieuc/tradingview",- "version": "4.0.0-beta.0",+ "version": "4.0.0-beta.1","license": "ISC","dependencies": {"ws": "^8.18.0"diff --git a/package.json b/package.jsonindex a30b834..e10c3f5 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@mathieuc/tradingview",- "version": "4.0.0-beta.0",+ "version": "4.0.0-beta.1","description": "TradingView market data for JavaScript and TypeScript: candles, quotes, indicators and strategies, with a simple data API and full low-level access.","type": "module","main": "./dist/index.js",