Skip to content

📈 Get real-time stocks from TradingView

Stabilize V4 lifecycle, coverage and release-candidate gates (#339)

Mathieu Colmonf007e7244739
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 29f7d74..ad607a2 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -28,6 +28,14 @@ jobs:
- run: npm run typecheck
- run: npm run lint
- run: npm test
+ if: matrix.node-version != '22.x'
+ - run: npm run test:coverage
+ if: matrix.node-version == '22.x'
+ - uses: actions/upload-artifact@v4
+ if: matrix.node-version == '22.x'
+ with:
+ name: unit-coverage
+ path: coverage/
- run: npm run build
- run: npm run smoke
diff --git a/.npmignore b/.npmignore
index 5d66a55..9622801 100644
--- a/.npmignore
+++ b/.npmignore
@@ -1,6 +1,5 @@
node_modules/
.github/
tests/
-examples/
scripts/
.env
diff --git a/README.md b/README.md
index 1da4998..81bce26 100644
--- a/README.md
+++ b/README.md
@@ -25,7 +25,7 @@ console.log(candles.at(-1)); // { time, open, high, low, close, volume }
Prefer to start without code? The setup paths below work too.
-> **Version 4 is a breaking rewrite** in TypeScript, with a new API and no compatibility layer. Coming from v3? Read the [migration guide](docs/migration-v4.md). Every v3 feature is still available: see the [coverage matrix](docs/v4-coverage.md) and [reliability evidence](docs/v4-reliability.md). npm versions 3.x keep the previous `Client` API; check the [npm page](https://www.npmjs.com/package/@mathieuc/tradingview) for the version you install.
+> **Version 4 is a breaking rewrite** in TypeScript, with a new API and no compatibility layer. Coming from v3? Read the [migration guide](docs/migration-v4.md). Every v3 feature is still available: see the [coverage matrix](docs/v4-coverage.md) and [reliability evidence](docs/v4-reliability.md). The [RC preparation report](docs/v4-stabilization.md) tracks current checks and remaining release gates. npm versions 3.x keep the previous `Client` API; check the [npm page](https://www.npmjs.com/package/@mathieuc/tradingview) for the version you install.
## Get started
@@ -95,6 +95,8 @@ const { values } = await getIndicatorData({
| Quotes: last price, change, bid/ask, volume... | `getQuote`, `getQuotes`, `watchQuotes` |
| Indicator values, drawings and strategy reports | `getIndicatorData`, `watchIndicator` |
| Symbol metadata | `getSymbolInfo` |
+| Stock/crypto screening and ranked lists | `getScreener`, `getHotlist` |
+| Account watchlists (read-only) | `getWatchlists` |
| Search and ratings | `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis` |
Websocket data functions accept `timeoutMs`, an `AbortSignal`, account `credentials`, and an optional shared `client`. HTTP lookups accept an `AbortSignal` through their options. Errors are `TradingViewError`s with a `code` such as `SYMBOL_ERROR`, `TIMEOUT` or `STUDY_ERROR`. Read the [data API guide](docs/data-api.md) for every option.
diff --git a/docs/README.es.md b/docs/README.es.md
index c1bf0af..670ac4a 100644
--- a/docs/README.es.md
+++ b/docs/README.es.md
@@ -35,7 +35,7 @@ const watcher = await watchCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '1' }
await watcher.stop();
```
-Cada función gestiona la conexión, el tiempo máximo (`timeoutMs`), la cancelación (`signal`) y la limpieza. Otras funciones: `getQuotes`, `watchQuotes`, `getSymbolInfo`, `getIndicatorData`, `watchIndicator`, `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis`. Detalles: [guía de la API de datos](data-api.md).
+Cada función gestiona la conexión, el tiempo máximo (`timeoutMs`), la cancelación (`signal`) y la limpieza. Otras funciones: `getQuotes`, `watchQuotes`, `getSymbolInfo`, `getIndicatorData`, `watchIndicator`, `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis`, `getScreener`, `getHotlist`, `getWatchlists`. Detalles: [guía de la API de datos](data-api.md).
## API de bajo nivel
diff --git a/docs/README.fr.md b/docs/README.fr.md
index e721ee6..6915e45 100644
--- a/docs/README.fr.md
+++ b/docs/README.fr.md
@@ -35,7 +35,7 @@ const watcher = await watchCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '1' }
await watcher.stop();
```
-Chaque fonction gère la connexion, le délai maximal (`timeoutMs`), l'annulation (`signal`) et le nettoyage. Autres fonctions : `getQuotes`, `watchQuotes`, `getSymbolInfo`, `getIndicatorData`, `watchIndicator`, `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis`. Détails : [guide de l'API de données](data-api.md).
+Chaque fonction gère la connexion, le délai maximal (`timeoutMs`), l'annulation (`signal`) et le nettoyage. Autres fonctions : `getQuotes`, `watchQuotes`, `getSymbolInfo`, `getIndicatorData`, `watchIndicator`, `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis`, `getScreener`, `getHotlist`, `getWatchlists`. Détails : [guide de l'API de données](data-api.md).
## API bas niveau
diff --git a/docs/README.pt.md b/docs/README.pt.md
index 9612faa..edce0cb 100644
--- a/docs/README.pt.md
+++ b/docs/README.pt.md
@@ -35,7 +35,7 @@ const watcher = await watchCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '1' }
await watcher.stop();
```
-Cada função cuida da conexão, do tempo máximo (`timeoutMs`), do cancelamento (`signal`) e da limpeza. Outras funções: `getQuotes`, `watchQuotes`, `getSymbolInfo`, `getIndicatorData`, `watchIndicator`, `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis`. Detalhes: [guia da API de dados](data-api.md).
+Cada função cuida da conexão, do tempo máximo (`timeoutMs`), do cancelamento (`signal`) e da limpeza. Outras funções: `getQuotes`, `watchQuotes`, `getSymbolInfo`, `getIndicatorData`, `watchIndicator`, `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis`, `getScreener`, `getHotlist`, `getWatchlists`. Detalhes: [guia da API de dados](data-api.md).
## API de baixo nível
diff --git a/docs/v4-backlog-triage.md b/docs/v4-backlog-triage.md
index a245f0a..29cb635 100644
--- a/docs/v4-backlog-triage.md
+++ b/docs/v4-backlog-triage.md
@@ -2,14 +2,14 @@
Baseline: `da67081` / published `4.0.0-beta.1`. Snapshot: **96 open issues and 8 open PRs**.
-Follow-up: #334 was merged on 3 October 2026. The focused fixes are included in the beta.2 release candidate. Reliability tools from #330 were subsequently ported without its stale version/README changes; the completed two-hour result is recorded in [reliability evidence](v4-reliability.md). Historical rows below describe the initial snapshot, not current PR state.
+Follow-up: #334 was merged on 3 October 2026. The focused fixes are included in the beta.2 release candidate. Reliability tools from #330 were subsequently ported without its stale version/README changes; the completed two-hour result is recorded in [reliability evidence](v4-reliability.md). The issue table below is refreshed through beta.5/stabilization; dated verification sections retain their original evidence.
This is an issue-by-issue disposition, not a claim that 96 bugs were reproduced or fixed.
Evidence comes from issue descriptions, current source/tests and the existing [coverage matrix](v4-coverage.md).
“Covered by code” is weaker than a targeted regression or live reproduction. “Needs” means keep open.
No issues/legacy PRs were closed, and no contributor comments were sent by this pass.
-## Immediate findings
+## Initial beta.1 findings (historical)
1. **Authentication gap:** PR #330 is still open. Its `/chart/` default and non-3xx redirect guard are absent from beta.1. This change ports only that focused fix with its regression test, not its old release/version text.
2. **Concrete missing feature:** #225 country/sector search filters implemented in this change, with deterministic query coverage and a public live endpoint probe.
@@ -18,9 +18,12 @@ No issues/legacy PRs were closed, and no contributor comments were sent by this
## Issues
+Current inventory: **95 open issues and 7 legacy open PRs** on 3 October 2026.
+Rows describe capability disposition, not automatic authorization to close reports.
+
| Issue | Disposition | Evidence / next action |
| --- | --- | --- |
-| [#321](https://github.com/Mathieu2301/TradingView-API/issues/321) getUser reports "Too many redirects" for HTTP 200 responses without auth_token | Partial → patched | The beta avoids missing-Location loops, but still starts at the homepage and follows a Location on HTTP 200. Ported the focused fix from PR #330; HTTP regression test passes. Not yet published. |
+| [#321](https://github.com/Mathieu2301/TradingView-API/issues/321) getUser reports "Too many redirects" for HTTP 200 responses without auth_token | Partial → patched | Published since beta.2: starts at /chart/ and follows Location only on 3xx. HTTP regression and authenticated live suite pass; CAPTCHA/WAF remains outside this fix. |
| [#319](https://github.com/Mathieu2301/TradingView-API/issues/319) More Control and access to data | Missing | Paper-trading account management and order execution are not exposed by V4. |
| [#313](https://github.com/Mathieu2301/TradingView-API/issues/313) History Create Session / Request History Data Features help | Missing / gated | No HistorySession or request_history_data implementation. PR #204 is a protocol reference, not V4-compatible code; requires entitled-account live validation. |
| [#312](https://github.com/Mathieu2301/TradingView-API/issues/312) tradingview wss is updated? | Needs reproduction | Current transport and timeouts are implemented, but the original connection timeout has no host/network trace. Capture exact endpoint, Node version and error on V4. |
@@ -49,7 +52,7 @@ No issues/legacy PRs were closed, and no contributor comments were sent by this
| [#232](https://github.com/Mathieu2301/TradingView-API/issues/232) Crypto Cap (e.g. CRYPTOCAP:TOTAL) symbols return "invalid symbol" | Needs reproduction | Issue is specifically CRYPTOCAP Replay, not ordinary candles. Test replay on TOTAL/OTHERS with an entitled account. |
| [#231](https://github.com/Mathieu2301/TradingView-API/issues/231) Missing data in examples/FromToData.js - provided date and custom date | Partial / server limits | getCandles from/to pagination is implemented; historical intraday availability remains server/account limited. Reproduce original window, not just a recent range. |
| [#230](https://github.com/Mathieu2301/TradingView-API/issues/230) os.version is not a function / Can't resolve 'os" | Unsupported environment | V4 targets Node/Bun and imports node:os/ws. Browser-extension support is not established by removing the old os.version call. |
-| [#225](https://github.com/Mathieu2301/TradingView-API/issues/225) Add additional filter on search market v3 | Missing → implemented | Added country/sector to searchMarkets, preserving exchange/type/offset. Unit coverage and public endpoint probe; not yet published. |
+| [#225](https://github.com/Mathieu2301/TradingView-API/issues/225) Add additional filter on search market v3 | Missing → implemented | Published since beta.2: country/sector filters preserve exchange/type/offset. Deterministic forwarding checks and public endpoint probe. |
| [#224](https://github.com/Mathieu2301/TradingView-API/issues/224) Default setting indicators | Partial | getIndicator provides defaults and PineIndicator.clone preserves a baseline. No reset-to-defaults convenience method; document reload/clone workflow. |
| [#223](https://github.com/Mathieu2301/TradingView-API/issues/223) Premium account doesn't return 20000 bars for server='prodata' | Needs entitled account | Pagination and credentials exist, but Premium/prodata 20k-bar entitlement is not proven with Basic. |
| [#222](https://github.com/Mathieu2301/TradingView-API/issues/222) Wrong or expired sessionid/signature - all time | Needs account reproduction | V4 credentials are { session, signature }; focused getUser patch helps page selection, but does not establish the original account entitlement or cookie validity. |
@@ -63,7 +66,7 @@ No issues/legacy PRs were closed, and no contributor comments were sent by this
| [#201](https://github.com/Mathieu2301/TradingView-API/issues/201) Private indicators | Needs private asset | Private listing/auth paths are implemented; specific invite-only access and private study values require an authorized matching script fixture. |
| [#199](https://github.com/Mathieu2301/TradingView-API/issues/199) Manage pine scripts | Missing | Pine permissions/listing are not script source create/update/delete APIs. |
| [#193](https://github.com/Mathieu2301/TradingView-API/issues/193) TypeError: str.replace is not a function - Handling Buffer Input in parseWSPacket | Covered by code | src/client/transport.ts converts Buffer, Buffer[] and ArrayBuffer to text before framing. Historical caller-specific environment not reproduced. |
-| [#192](https://github.com/Mathieu2301/TradingView-API/issues/192) 15 minutes delay for MOEX market | Upstream entitlement / missing | Exchange real-time rights and server delays must be checked with that venue/account. General stock screener API is not implemented. |
+| [#192](https://github.com/Mathieu2301/TradingView-API/issues/192) 15 minutes delay for MOEX market | Upstream entitlement / missing | Exchange real-time rights and server delays must be checked with that venue/account. getScreener is available since beta.3, but does not grant exchange real-time rights. |
| [#191](https://github.com/Mathieu2301/TradingView-API/issues/191) How to install? | Covered | README installation/quick start, docs/data-api.md and examples cover the requested entry point; package consumer smoke passes. |
| [#188](https://github.com/Mathieu2301/TradingView-API/issues/188) Pine 'referencing length of a series' error after about 12 hours | Needs long-run reproduction | 12-hour Pine max_bars_back failure is not a normal indicator input. Need script and long-running capture; short endurance runs cannot resolve it. |
| [#184](https://github.com/Mathieu2301/TradingView-API/issues/184) Proxy support | Partial | Custom WebSocket transport and HTTP fetch hooks permit adapters, but no documented/tested unified proxy configuration. PR #208 cannot be merged unchanged. |
@@ -104,27 +107,27 @@ No issues/legacy PRs were closed, and no contributor comments were sent by this
| [#101](https://github.com/Mathieu2301/TradingView-API/issues/101) FakeReplay always returning the same day | Needs targeted regression | Negative-count history is live-tested generally; exact repeated-day/gap cases and exchange holidays still need reproduction. |
| [#89](https://github.com/Mathieu2301/TradingView-API/issues/89) No "strategyReport.trades" data for private strategy backtest | Needs private asset | Public and compressed reports are proven; missing trades for the specific private strategy is not yet reproduced. |
| [#88](https://github.com/Mathieu2301/TradingView-API/issues/88) Data point is missing in FakeReplayMode example output | Needs targeted regression | Negative-count history is live-tested generally; exact repeated-day/gap cases and exchange holidays still need reproduction. |
-| [#87](https://github.com/Mathieu2301/TradingView-API/issues/87) Feature : get watchlists | Missing | No watchlist or hotlist API; useful next discovery target alongside screener. |
-| [#85](https://github.com/Mathieu2301/TradingView-API/issues/85) Question : Can you enable stock screener real-time ? | Upstream entitlement / missing | Exchange real-time rights and server delays must be checked with that venue/account. General stock screener API is not implemented. |
+| [#87](https://github.com/Mathieu2301/TradingView-API/issues/87) Feature : get watchlists | Covered with live limits | Published in beta.4: getWatchlists and scanner-ranked getHotlist. Populated lists are fixture-tested; available account lists are empty. UI parity is not claimed. |
+| [#85](https://github.com/Mathieu2301/TradingView-API/issues/85) Question : Can you enable stock screener real-time ? | Upstream entitlement / missing | Exchange real-time rights and server delays must be checked with that venue/account. getScreener is available since beta.3, but does not grant exchange real-time rights. |
| [#84](https://github.com/Mathieu2301/TradingView-API/issues/84) Alerts feature | Missing | No TradingView alert CRUD or triggered-alert subscription. Local quote/study listeners are not server-side alerts. |
| [#83](https://github.com/Mathieu2301/TradingView-API/issues/83) how to get update data of strategy.entry trigger signal. | Partial | Strategy reports and study updates exist; no dedicated exactly-once strategy.entry signal stream. Application must distinguish intrabar updates. |
| [#80](https://github.com/Mathieu2301/TradingView-API/issues/80) [V3] Same output multiple times | Needs reproduction | Repeated update events may be intrabar updates or study lifecycle effects. No evidence yet of a V4 fix for this exact script. |
| [#79](https://github.com/Mathieu2301/TradingView-API/issues/79) Where can I find the chart_id for getDrawings? | Partial documentation | getDrawings supports chartId/layout inputs, but extracting the correct internal chart ID needs a saved-layout example and private validation. |
| [#73](https://github.com/Mathieu2301/TradingView-API/issues/73) Strategy Optimization Steps | Partial | Inputs and reports exist; no bounded optimization runner, date-window Deep Backtest or throttle-aware multithreading API. |
| [#66](https://github.com/Mathieu2301/TradingView-API/issues/66) Maximum number of studies per chart has been reached | Upstream limits | Server study/session/calculation limits are not removed by V4. Bound concurrency, release sessions and reproduce account-specific thresholds; no bulk retry flood. |
-| [#53](https://github.com/Mathieu2301/TradingView-API/issues/53) Stock Screener API | Missing | No general stock screener API; getTechnicalAnalysis is only a fixed-column ratings request. |
+| [#53](https://github.com/Mathieu2301/TradingView-API/issues/53) Stock Screener API | Covered HTTP API | Published in beta.3: getScreener supports columns, filters, ranking and pagination; deterministic and anonymous live checks. Not a push subscription. |
| [#51](https://github.com/Mathieu2301/TradingView-API/issues/51) Adding some sort of documentation | Covered | README installation/quick start, docs/data-api.md and examples cover the requested entry point; package consumer smoke passes. |
| [#30](https://github.com/Mathieu2301/TradingView-API/issues/30) Can I Hire You To Set This Up For Me? | Administrative | Collaboration/service proposal, not a reproducible library defect. No unsolicited outreach in this triage. |
| [#24](https://github.com/Mathieu2301/TradingView-API/issues/24) Renko chart's indicator value does not match GUI-based TradingView's, given same configurations | Needs parity reproduction | Renko chart type is live-tested, but this exact multi-timeframe study/GUI value mismatch is not. Need matched bars, inputs and account. |
-## Open pull requests
+## Legacy pull requests
| PR | Verified disposition | Next action |
| --- | --- | --- |
-| [#330](https://github.com/Mathieu2301/TradingView-API/pull/330) | **Not merged.** Auth fix, parity/endurance scripts and recovery live test remain useful. Version/release prose is stale. | Focused auth port included here. Retain/rebase remaining reliability work; recover saved endurance results before claiming completion. |
+| [#330](https://github.com/Mathieu2301/TradingView-API/pull/330) | Closed/superseded after focused ports in #334/#335. Authentication, parity/endurance tooling and recovery checks are included in beta.2. | No remaining code port from this PR is needed for the documented scope; the recovered two-hour result is in reliability evidence. |
| [#322](https://github.com/Mathieu2301/TradingView-API/pull/322) | Legacy V3 authentication patch; not directly applicable to TS V4. | Its chart-page/status semantics are carried through #330 into this port. Decide V3 backport separately while latest is 3.5.2. |
| [#320](https://github.com/Mathieu2301/TradingView-API/pull/320) | V3 this-binding patch. V4 HTTP functions are standalone, not receiver-based. | Superseded for V4; possible V3 maintenance value. |
-| [#318](https://github.com/Mathieu2301/TradingView-API/pull/318) | Binding fix is superseded, but dependency upgrade is **not** automatically superseded: The baseline still uses Vitest 3. | Audit confirmed GHSA-82fw-gwwq-j7x9 in Vitest/mocker. Updated to patched Vitest 4.1.11+ in this change; not the older vulnerable 4.1.9 from the PR. |
+| [#318](https://github.com/Mathieu2301/TradingView-API/pull/318) | V4 uses standalone HTTP functions and patched Vitest 4.1.11. The original Vitest 3 baseline no longer applies. | Audit confirmed GHSA-82fw-gwwq-j7x9 in Vitest/mocker. Updated to patched Vitest 4.1.11+ in this change; not the older vulnerable 4.1.9 from the PR. |
| [#289](https://github.com/Mathieu2301/TradingView-API/pull/289) | General chart event registration exists via Emitter.on/onAny and event tests. | Superseded for V4; no need to port V3 callback storage. |
| [#219](https://github.com/Mathieu2301/TradingView-API/pull/219) | Native TS build emits declarations and package smoke compiles a strict consumer. | Superseded for V4; avoid stale generated V3 declarations. |
| [#208](https://github.com/Mathieu2301/TradingView-API/pull/208) | Axios/ws proxy patch targets removed V3 architecture. V4 offers transport/fetch injection, not a turnkey proxy. | Preserve intent; implement/test an adapter recipe across both HTTP and WS before resolving #184. |
@@ -143,7 +146,7 @@ No issues/legacy PRs were closed, and no contributor comments were sent by this
Beta.3 adds `getScreener` for #53 and scanner fields relevant to #280. See
[screener documentation](screener.md). #85 real-time exchange entitlement is not
-resolved by a successful HTTP scan. Watchlists and paid/private cases remain open.
+resolved by a successful HTTP scan. Watchlists shipped subsequently in beta.4; paid/private case limitations remain.
## Watchlist follow-up
diff --git a/docs/v4-coverage.md b/docs/v4-coverage.md
index 0f8cede..fe5da50 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; 118 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; 135 tests in the stabilization candidate, both green). Websocket tests include the native Node/Bun transport against a loopback server (`tests/unit/transport.test.ts`), 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;
@@ -16,6 +16,25 @@ Beta.2 follow-up on **3 October 2026**: all 22 current live tests passed locally
Test names are abbreviated as `file › test`.
+## Stabilization checks — 3 October 2026
+
+`npm run test:coverage` measures **source files only** with V8 (test helpers are excluded).
+The CI Node 22 job enforces minimums of 90% lines, 85% statements/functions and 75%
+branches, and uploads the HTML/JSON report. These are regression floors, not claims
+of universal behavior. Network/account coverage is tracked independently below.
+See the [stabilization report](v4-stabilization.md) for release gates and current results.
+
+| Capability / failure path | Deterministic evidence | Live evidence / limit |
+| --- | --- | --- |
+| Screener pagination, fields, types and errors | `screener.test.ts` | `live/data.test.ts`: requested BTC symbol and price |
+| Ranked lists (four kinds) | `watchlists.test.ts` | `live/data.test.ts`: populated volume ranking; not UI parity |
+| Read-only account watchlists | `watchlists.test.ts`: populated lists, sections, metadata, auth failures | `live/authenticated.test.ts`: read-only response; available lists are empty |
+| HTTP response stream failure / cancellation | `http.test.ts`: typed HTTP_ERROR / ABORTED after headers | Simulated, not an upstream failure claim |
+| Authentication cancelled by close, disconnect or timeout | `client.test.ts`: request aborted, no late AUTH_ERROR or auth packet | Simulated lifecycle failures |
+| Empty/malformed auth token or rejected HTTP page | `http.test.ts`: AUTH_ERROR | Existing authenticated suite checks successful lookup |
+| Native websocket framing, Origin and handshake failure | `transport.test.ts`: real loopback websocket under both runners | Does not reproduce DNS, proxy or internet loss |
+| Published exports and declarations | `scripts/smoke.mjs`: tarball, Node/Bun, require(esm), strict TS including discovery APIs | No TradingView access in smoke |
+
## Package and tooling
| v3 capability | v4 | Unit evidence | Live |
@@ -111,7 +130,7 @@ Test names are abbreviated as `file › test`.
| `PineIndicator` getters (`pineId`, `pineVersion`, description, inputs, plots, script, type) and `setType` | `id`, `version`, same others; `setType`, `clone` | `indicators › clones independently...` | ✅ (`sessions › loads Pine indicator definitions`) |
| `PineIndicator.setOption` (by `in_N`, number, inline name, internal ID; type and option checks) | `setInput`, `setInputs`, `findInput` | `indicators › finds inputs by ID...` | ✅ (definition-level) |
| `BuiltInIndicator(type)`, defaults for Volume and volume profiles, `setOption(key, value, FORCE)` | Same (+ initial options; time defaults computed per instance instead of at import) | `indicators › BuiltInIndicator › *` | ✅ (`Volume`, `VbPFixed@tv-basicstudies-241!`) |
-| `getIndicator(id, version, session, signature)` (pine-facade translate, input/plot naming) | `getIndicator(id, { version, credentials })`, `parseIndicatorDefinition` | `indicators › parseIndicatorDefinition...`, `http › loads an indicator definition...`, `throws NOT_FOUND...` | ✅ public scripts; 🔒 private/invite-only |
+| `getIndicator(id, version, session, signature)` (pine-facade translate, input/plot naming) | `getIndicator(id, { version, credentials })`, `parseIndicatorDefinition` | `indicators › parseIndicatorDefinition...`, `http › loads an indicator definition...`, `throws NOT_FOUND...` | ✅ public scripts and six saved USER scripts; 🔒 original invite-only issue fixtures |
| (new) One-shot / streaming indicator values | `getIndicatorData`, `watchIndicator` | `data › indicator data › *` | ✅ built-in and one-shot Pine RSI with account; Pine stream unit-tested |
## Quotes
@@ -137,7 +156,7 @@ Test names are abbreviated as `file › test`.
| `getTA(symbol)` (8 periods × All/MA/Other, scaled) | `getTechnicalAnalysis(symbol)` (`null` instead of `false` without data) | `http › getTechnicalAnalysis › *` | ✅ |
| `searchIndicator(text)` (built-in lists cached + community suggestions, access mapping) | `searchIndicators(text)`, `clearIndicatorCache()` | `http › searches built-in and community indicators` | ✅ |
| `result.get()` on indicator results | `getIndicator(result.id, { version: result.version })` | `http › loads an indicator definition...` | ✅ |
-| `getPrivateIndicators(session, signature)` | `getPrivateIndicators(credentials)` | `http › lists private indicators with credentials` | ✅ authenticated listing endpoint; actual private item not available |
+| `getPrivateIndicators(session, signature)` | `getPrivateIndicators(credentials)` | `http › lists private indicators with credentials` | ✅ authenticated listing; six saved USER scripts evaluated separately (see reliability evidence) |
| `loginUser(username, password, remember, UA)` | `loginUser({ username, password, remember, userAgent })` (form now URL-encoded) | `http › loginUser posts an encoded form and reads cookies` | 🔒 |
| `getUser(session, signature, location)` with redirect-loop protection | `getUser(credentials, { location, maxRedirects })` (relative redirects resolved) | `http › getUser parses the account page...`, `getUser stops redirect loops...` | ✅ authenticated success and wrong-cookie rejection |
| `getChartToken(layout, credentials)` | `getChartToken(layoutId, { userId, credentials })` | `http › gets a chart token...` | 🔒 (needs a layout ID) |
diff --git a/docs/v4-stabilization.md b/docs/v4-stabilization.md
new file mode 100644
index 0000000..bde43dc
--- /dev/null
+++ b/docs/v4-stabilization.md
@@ -0,0 +1,87 @@
+# V4 stabilization and release-candidate gates
+
+Snapshot: 3 October 2026, starting from beta.5 (`b793115`).
+The source/package version is staged as **4.0.0-rc.0**. This is a prepared candidate,
+not a claim of npm publication or promotion of `latest`. Install the published beta
+until the candidate is released. [Migration guide](migration-v4.md).
+
+## What changed
+
+- Normalize failures while consuming an HTTP response body, not only while fetching
+ headers. Cancellation remains `ABORTED`; other stream failures become `HTTP_ERROR`.
+- Cancel pending account lookup when the client closes, disconnects or times out.
+ An intentional cancellation must not emit a late `AUTH_ERROR` or send an auth packet.
+- Reject empty/malformed account tokens and token-like content in rejected HTTP pages.
+- Exercise the real Node/Bun websocket transport against a Node loopback fixture:
+ Origin/custom headers, Unicode binary decoding, remote close and failed handshake.
+- Add repeatable live scanner, ranked-list and read-only watchlist checks.
+- Add source-only V8 coverage with CI floors and downloadable HTML/JSON evidence.
+- Extend packed-consumer checks to discovery exports and types; include examples,
+ assets, the agent index and parity diagnostic in the tarball.
+- Refresh the capability/backlog tables without closing unreproduced historical issues.
+
+## Deterministic evidence
+
+| Check | Result |
+| --- | --- |
+| Typecheck, lint, build | Passed locally |
+| Node unit suite | 135 passed, 14 files |
+| Bun unit suite | 135 passed, 14 files |
+| Source lines | 95.21% (1,235 / 1,297) |
+| Source statements | 92.62% (1,394 / 1,505) |
+| Source functions | 94.73% (342 / 361) |
+| Source branches | 83.67% (820 / 980) |
+| Dependency audit | Zero reported vulnerabilities at install |
+| Packed consumer | Node ESM, Node require(esm), Bun and strict TypeScript |
+
+Negative control: the six new lifecycle/body/token regression scenarios were run
+against unmodified beta.5 source; all six failed as expected. Restoring the candidate
+source makes all six pass. This verifies that the assertions detect the actual defects.
+
+Run `npm ci && npm run check`, `npm run test:bun` and `npm run test:coverage`.
+Coverage excludes test helpers and is **not** a measure of TradingView symbols,
+permissions, server behavior, GUI parity or account-feature completeness. Loopback
+handshake tests do not establish DNS/proxy/internet-failure coverage.
+
+CI runs deterministic checks on Node 20/22/24 and Bun. Node 22 additionally measures
+coverage with floors of 90% lines, 85% statements/functions and 75% branches.
+A growing test count is not itself a release gate; assertions and tested behavior matter.
+
+## Live evidence
+
+The local candidate suite passed **19 anonymous tests**; **six authenticated tests
+were skipped**, not passed, because credentials were not loaded into that run.
+The [manual authenticated CI run](https://github.com/Mathieu2301/TradingView-API/actions/runs/37149955645)
+on candidate commit `8e0e564` subsequently passed **all 25 tests**, including all six
+account tests (none skipped). Its Node 20/22/24 and Bun jobs also passed. A green
+workflow with a non-blocking failed live job or skipped account tests is insufficient.
+
+Earlier beta evidence remains in [reliability evidence](v4-reliability.md): six
+private USER scripts, 22 authenticated-suite tests, BTC updates after 30 heartbeats,
+and a two-hour rotating-connection endurance run. These are distinct observations,
+not substitutes for running the current candidate or reproducing original reports.
+
+## Release gates and explicit non-goals
+
+| Gate / limitation | Disposition |
+| --- | --- |
+| Candidate deterministic CI and package consumption | Passed on Node 20/22/24 and Bun in the linked CI run |
+| Current authenticated live suite | Passed: 25/25 in the linked manual CI run |
+| Open-market EUR/USD HeikinAshi after 30 heartbeats | Scheduled for Monday 5 October, 09:00 Europe/Paris; remains pending |
+| Populated account watchlists | Deterministic fixtures only; do not modify account content just to manufacture coverage |
+| Deep Backtesting | Not shipped; available account returned `not_allowed` |
+| Renko GUI parity, subscribed CME, original private scripts and 12-hour Pine issue | Matching assets/reproduction needed; no resolution claimed |
+| Automatic reconnection / server-side alerts / trading execution | Outside this release's scope |
+
+Do not promote npm `latest` (still V3) as part of candidate preparation. Once the
+remaining required evidence is reviewed, publish the exact validated candidate
+under a prerelease tag, verify registry installation on Node/Bun, and record the
+published integrity/version. A stable V4 release is a separate promotion decision.
+
+## Cleanup
+
+The 13 initial local worktrees were inventoried. Two clean, fully ancestral
+worktrees were removed; the old beta.1 tarball was retained separately. Branch
+references were kept. The primary managed project, worktrees with local context,
+and divergent/squash-merged branches were retained rather than assuming ancestry.
+No remote branches, contributor PRs, account data or historical issues were deleted.
diff --git a/examples/README.md b/examples/README.md
index 323d157..86b87f0 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -17,6 +17,7 @@ Examples that need an account read the `SESSION` and `SIGNATURE` cookies from th
| [watch-candles.js](watch-candles.js) | `watchCandles` | No |
| [quotes.js](quotes.js) | `getQuote`, `getQuotes`, `watchQuotes` | No |
| [indicator-data.js](indicator-data.js) | `getIndicatorData` | Pine scripts only |
+| [screener.js](screener.js) | `getScreener` (filters, columns, ranking) | No |
| [search.js](search.js) | `searchMarkets`, `searchIndicators`, `getTechnicalAnalysis` | No |
| [custom-chart-types.js](custom-chart-types.js) | Heikin Ashi, Renko, Line Break, Kagi, P&F, Range | No (daily) |
| [errors.js](errors.js) | `TradingViewError` codes | Partly |
diff --git a/llms.txt b/llms.txt
index 9605fcd..ccc4cfb 100644
--- a/llms.txt
+++ b/llms.txt
@@ -10,6 +10,9 @@ Simple data API (import from '@mathieuc/tradingview/data' or the root entry):
- watchCandles(query, { onData, onError? }) -> watcher { latest, stop(), closed }.
- getQuote(symbol), getQuotes({ symbols }), watchQuotes({ symbols }, { onData }).
- getSymbolInfo(symbol), getIndicatorData({ symbol, indicator, inputs? }), watchIndicator(...).
+- getScreener({ columns, market?, filter?, sort?, range?, symbols? }) -> { totalCount, rows }; one HTTP page, not a streaming screener.
+- getHotlist({ kind, ... }) -> scanner-ranked rows, not guaranteed TradingView UI parity.
+- getWatchlists({ credentials }) -> read-only account lists with ordered symbols and section markers.
- searchMarkets(text), searchIndicators(text), getTechnicalAnalysis(symbol).
- Websocket data calls accept timeoutMs, signal (AbortSignal), credentials ({ session, signature }) and client (shared TradingViewClient). HTTP lookups accept signal in options.
- Candle calls can use a custom MarketDataProvider; TradingViewProvider is the default source adapter.
diff --git a/package-lock.json b/package-lock.json
index d2df6c4..a7c1f20 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@mathieuc/tradingview",
- "version": "4.0.0-beta.5",
+ "version": "4.0.0-rc.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@mathieuc/tradingview",
- "version": "4.0.0-beta.5",
+ "version": "4.0.0-rc.0",
"license": "ISC",
"dependencies": {
"ws": "^8.18.0"
@@ -15,6 +15,7 @@
"@eslint/js": "^9.39.0",
"@types/node": "^22.20.5",
"@types/ws": "^8.18.1",
+ "@vitest/coverage-v8": "^4.1.11",
"eslint": "^9.39.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.0",
@@ -24,6 +25,66 @@
"node": ">=20.0.0"
}
},
+ "node_modules/@babel/helper-string-parser": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
+ "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-identifier": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
+ "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/parser": {
+ "version": "7.29.9",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
+ "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.29.8"
+ },
+ "bin": {
+ "parser": "bin/babel-parser.js"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@babel/types": {
+ "version": "7.29.8",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
+ "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-string-parser": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@bcoe/v8-coverage": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz",
+ "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@eslint-community/eslint-utils": {
"version": "4.10.1",
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz",
@@ -234,6 +295,16 @@
"url": "https://github.com/sponsors/nzakas"
}
},
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
@@ -241,6 +312,17 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
"node_modules/@oxc-project/types": {
"version": "0.152.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.152.0.tgz",
@@ -872,6 +954,37 @@
"url": "https://opencollective.com/eslint"
}
},
+ "node_modules/@vitest/coverage-v8": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.11.tgz",
+ "integrity": "sha512-8MVGEFnJIcdGjcbfKmeq8z0pZHH0JlVtoVZH9Q/qwUp6wyFnEJUBMrw9DCaj+ra3vShGmhavjalMIhPNxZAUcw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@bcoe/v8-coverage": "^1.0.2",
+ "@vitest/utils": "4.1.11",
+ "ast-v8-to-istanbul": "^1.0.0",
+ "istanbul-lib-coverage": "^3.2.2",
+ "istanbul-lib-report": "^3.0.1",
+ "istanbul-reports": "^3.2.0",
+ "magicast": "^0.5.2",
+ "obug": "^2.1.1",
+ "std-env": "^4.0.0-rc.1",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@vitest/browser": "4.1.11",
+ "vitest": "4.1.11"
+ },
+ "peerDependenciesMeta": {
+ "@vitest/browser": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@vitest/expect": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz",
@@ -1058,6 +1171,18 @@
"node": ">=12"
}
},
+ "node_modules/ast-v8-to-istanbul": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.7.tgz",
+ "integrity": "sha512-kFL68AG6ajd8fg248zwM9GQrUWEp79gsmjum34OEXjs4yHuUMZfYKwOLW9GMmB4oNvVrj+EAGxsP7ye2UR9UlA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/trace-mapping": "^0.3.31",
+ "estree-walker": "^3.0.3",
+ "js-tokens": "^10.0.0"
+ }
+ },
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -1533,6 +1658,13 @@
"node": ">=8"
}
},
+ "node_modules/html-escaper": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
+ "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
@@ -1600,6 +1732,52 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/istanbul-lib-coverage": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
+ "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/istanbul-lib-report": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
+ "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "istanbul-lib-coverage": "^3.0.0",
+ "make-dir": "^4.0.0",
+ "supports-color": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/istanbul-reports": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz",
+ "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "html-escaper": "^2.0.0",
+ "istanbul-lib-report": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/js-tokens": {
+ "version": "10.0.0",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz",
+ "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/js-yaml": {
"version": "4.3.2",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",
@@ -1974,6 +2152,34 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
+ "node_modules/magicast": {
+ "version": "0.5.5",
+ "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz",
+ "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.29.7",
+ "@babel/types": "^7.29.7",
+ "source-map-js": "^1.2.1"
+ }
+ },
+ "node_modules/make-dir": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
+ "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "semver": "^7.5.3"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/minimatch": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
diff --git a/package.json b/package.json
index 3244365..93fc8ea 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@mathieuc/tradingview",
- "version": "4.0.0-beta.5",
+ "version": "4.0.0-rc.0",
"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",
@@ -23,7 +23,11 @@
"README.md",
"docs",
"scripts/endurance.mjs",
- "scripts/probe-account.mjs"
+ "scripts/probe-account.mjs",
+ "assets",
+ "llms.txt",
+ "examples",
+ "scripts/parity.mjs"
],
"sideEffects": false,
"scripts": {
@@ -39,7 +43,8 @@
"prepack": "npm run build",
"probe:endurance": "npm run build && node scripts/endurance.mjs",
"probe:parity": "npm run build && node scripts/parity.mjs",
- "probe:account": "npm run build && node scripts/probe-account.mjs"
+ "probe:account": "npm run build && node scripts/probe-account.mjs",
+ "test:coverage": "vitest run --coverage"
},
"repository": {
"type": "git",
@@ -70,6 +75,7 @@
"@eslint/js": "^9.39.0",
"@types/node": "^22.20.5",
"@types/ws": "^8.18.1",
+ "@vitest/coverage-v8": "^4.1.11",
"eslint": "^9.39.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.0",
diff --git a/scripts/smoke.mjs b/scripts/smoke.mjs
index 4eba87d..a16a039 100644
--- a/scripts/smoke.mjs
+++ b/scripts/smoke.mjs
@@ -1,7 +1,7 @@
#!/usr/bin/env node
// Packs the library, installs the tarball in a temporary project and checks
// that both entry points load (ESM + type declarations) under Node and Bun.
-// Network is not required: no TradingView call is made.
+// No TradingView call is made; installing the tarball may access the npm registry.
import { execFileSync, spawnSync } from 'node:child_process';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -21,7 +21,7 @@ const dir = mkdtempSync(join(tmpdir(), 'tv-smoke-'));
try {
const packed = JSON.parse(run('npm', ['pack', '--json', '--pack-destination', dir], root))[0];
const files = packed.files.map((f) => f.path);
- for (const required of ['dist/index.js', 'dist/index.d.ts', 'dist/data/index.js', 'dist/data/index.d.ts', 'README.md']) {
+ for (const required of ['dist/index.js', 'dist/index.d.ts', 'dist/data/index.js', 'dist/data/index.d.ts', 'README.md', 'llms.txt', 'scripts/endurance.mjs', 'scripts/probe-account.mjs', 'scripts/parity.mjs', 'examples/screener.js']) {
if (!files.includes(required)) throw new Error(`Missing ${required} in package`);
}
if (files.some((f) => f.startsWith('src/') || f.startsWith('tests/'))) throw new Error('Sources or tests leaked into package');
@@ -35,6 +35,9 @@ try {
import { getCandles, watchQuotes, TradingViewError, TradingViewProvider } from '@mathieuc/tradingview/data';
const pkg = JSON.parse(await (await import('node:fs/promises')).readFile(new URL(import.meta.resolve('@mathieuc/tradingview/package.json')), 'utf8'));
if (typeof tv.TradingViewClient !== 'function' || typeof getCandles !== 'function' || typeof watchQuotes !== 'function' || typeof TradingViewProvider !== 'function') throw new Error('exports missing');
+ for (const name of ['getScreener', 'getWatchlists', 'getHotlist', 'summarizeStrategyReport']) {
+ if (typeof tv[name] !== 'function') throw new Error('missing export: ' + name);
+ }
if (tv.getCandles !== getCandles) throw new Error('entry points disagree');
const frame = tv.protocol.encodePacket('set_auth_token', ['x']);
if (tv.protocol.decodeFrames(frame)[0].packet.m !== 'set_auth_token') throw new Error('protocol roundtrip failed');
@@ -65,14 +68,17 @@ try {
const tsc = join(root, 'node_modules', 'typescript', 'bin', 'tsc');
writeFileSync(join(dir, 'consumer.ts'), `
import { getCandles, TradingViewProvider, type Candle, type MarketDataProvider } from '@mathieuc/tradingview/data';
- import { TradingViewClient, type StudyValue } from '@mathieuc/tradingview';
+ import { getScreener, getHotlist, getWatchlists, type ScreenerResult, type Watchlist, TradingViewClient, type StudyValue } from '@mathieuc/tradingview';
const candles: Promise<Candle[]> = getCandles({ symbol: 'BINANCE:BTCUSDT', timeframe: '60', count: 10 });
const client = new TradingViewClient();
const chart = client.createChart();
chart.on('update', (changes: string[]) => console.log(changes, chart.candles.at(-1)?.close));
const row: StudyValue = { $time: 1 };
const provider: MarketDataProvider = new TradingViewProvider();
- void candles; void row; void provider;
+ const scan: Promise<ScreenerResult> = getScreener({ columns: ['close'], range: [0, 10] });
+ const ranked: Promise<ScreenerResult> = getHotlist({ kind: 'gainers' });
+ const lists: Promise<Watchlist[]> = getWatchlists({ credentials: { session: 'fixture' } });
+ void scan; void ranked; void lists; void candles; void row; void provider;
`);
writeFileSync(join(dir, 'tsconfig.json'), JSON.stringify({
compilerOptions: { module: 'NodeNext', moduleResolution: 'NodeNext', target: 'ES2022', strict: true, noEmit: true, types: [], lib: ['ES2022', 'DOM'] },
diff --git a/src/client/client.ts b/src/client/client.ts
index d790411..70a890b 100644
--- a/src/client/client.ts
+++ b/src/client/client.ts
@@ -81,6 +81,8 @@ export class TradingViewClient extends Emitter<ClientEvents> {
#authToken?: string;
+ readonly #authController = new AbortController();
+
#closed = false;
#closing = false;
@@ -140,13 +142,14 @@ export class TradingViewClient extends Emitter<ClientEvents> {
if (options.authToken) {
this.#authToken = options.authToken;
} else if (options.credentials?.session) {
- getUser(options.credentials, { location: options.location, fetch: options.fetch })
+ getUser(options.credentials, { location: options.location, fetch: options.fetch, signal: this.#authController.signal })
.then((user) => {
- if (this.#closed) return;
+ if (this.#closed || this.#closing) return;
this.#authToken = user.authToken;
this.#authenticate();
})
.catch((error) => {
+ if (this.#closed || this.#closing) return;
this.#fail(new TradingViewError('AUTH_ERROR', `Credentials error: ${toTradingViewError(error).message}`, {
cause: error,
}));
@@ -221,6 +224,7 @@ export class TradingViewClient extends Emitter<ClientEvents> {
this.#closeRequested = true;
if (this.#closing) return;
this.#closing = true;
+ this.#authController.abort();
// Do not hang if the server never acknowledges the close.
setTimeout(() => this.#onClose(1000, 'Close timeout'), 3_000).unref?.();
this.#transport.close();
@@ -300,6 +304,7 @@ export class TradingViewClient extends Emitter<ClientEvents> {
if (wasReady || this.hasListeners('error')) this.emit('error', error);
if (!wasReady || error.code === 'AUTH_ERROR' || error.code === 'CONNECTION_ERROR') {
this.#closing = true;
+ this.#authController.abort();
this.#transport.close();
// Some transports never emit close after a failed handshake.
setTimeout(() => this.#onClose(undefined, error.message), 3_000).unref?.();
@@ -309,6 +314,7 @@ export class TradingViewClient extends Emitter<ClientEvents> {
#onClose(code?: number, reason?: string): void {
if (this.#closed) return;
this.#closed = true;
+ this.#authController.abort();
this.#authenticated = false;
clearTimeout(this.#readyTimer);
this.#log?.('close', code, reason);
diff --git a/src/http/account.ts b/src/http/account.ts
index 28a9a05..6b13030 100644
--- a/src/http/account.ts
+++ b/src/http/account.ts
@@ -161,7 +161,10 @@ export async function getUser(credentials: Credentials, options: GetUserOptions
for (let redirects = 0; ; redirects += 1) {
const { status, text, headers } = await request(location, { credentials, redirect: 'manual' }, options);
- if (text.includes('auth_token')) return parseUserPage(text, credentials);
+ if (status >= 200 && status < 300 && text.includes('auth_token')) {
+ const user = parseUserPage(text, credentials);
+ if (user.authToken) return user;
+ }
const next = headers.get('location');
const resolved = status >= 300 && status < 400 && next ? new URL(next, location).toString() : undefined;
diff --git a/src/http/request.ts b/src/http/request.ts
index 491e69a..09a42e0 100644
--- a/src/http/request.ts
+++ b/src/http/request.ts
@@ -94,6 +94,7 @@ export async function request(url: string, init: RequestInit, options: HttpOptio
const fetchImpl = options.fetch ?? globalThis.fetch;
let response: Response;
+ let text: string;
try {
response = await fetchImpl(target.toString(), {
method: init.method ?? (body === undefined ? 'GET' : 'POST'),
@@ -102,11 +103,11 @@ export async function request(url: string, init: RequestInit, options: HttpOptio
redirect: init.redirect ?? 'follow',
signal: options.signal,
});
+ text = await response.text();
} catch (error) {
throw toTradingViewError(error, 'HTTP_ERROR');
}
- const text = await response.text();
if (response.status >= 500) {
throw new TradingViewError('HTTP_ERROR', `${target.host} answered HTTP ${response.status}`, {
details: { status: response.status, body: text.slice(0, 500) },
diff --git a/tests/helpers/native-server.mjs b/tests/helpers/native-server.mjs
new file mode 100644
index 0000000..48fe567
--- /dev/null
+++ b/tests/helpers/native-server.mjs
@@ -0,0 +1,17 @@
+// Node loopback fixture used by both runners; no external endpoint involved.
+import { Buffer } from 'node:buffer';
+import { createServer } from 'node:http';
+import { WebSocketServer } from 'ws';
+const server = createServer((_request, response) => { response.writeHead(503); response.end(); });
+if (process.argv[2] === 'echo') {
+ const websocket = new WebSocketServer({ server });
+ websocket.on('connection', (socket, request) => {
+ socket.on('message', (data) => {
+ socket.send(Buffer.from(JSON.stringify({
+ origin: request.headers.origin, header: request.headers['x-test'], echo: data.toString(),
+ })));
+ socket.close(1000, 'finished');
+ });
+ });
+}
+server.listen(0, '127.0.0.1', () => console.log(server.address().port));
diff --git a/tests/live/authenticated.test.ts b/tests/live/authenticated.test.ts
index 03d1eb6..5331b8f 100644
--- a/tests/live/authenticated.test.ts
+++ b/tests/live/authenticated.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import {
- getCandles, getIndicator, getIndicatorData, getPrivateIndicators, getUser, TradingViewClient,
+ getWatchlists, getCandles, getIndicator, getIndicatorData, getPrivateIndicators, getUser, TradingViewClient,
} from '../../src/index.js';
import { credentials, LIVE } from './env.js';
@@ -35,6 +35,16 @@ describe.skipIf(!LIVE || !credentials)('live: authenticated', () => {
expect(result.strategyReport.performance.all?.totalTrades).toBeTypeOf('number');
});
+ it('reads watchlists without changing account content', async () => {
+ const lists = await getWatchlists({ credentials: auth, signal: AbortSignal.timeout(15_000) });
+ expect(Array.isArray(lists)).toBe(true);
+ for (const list of lists) {
+ expect(list.id).toBeTypeOf('number');
+ expect(list.name).toBeTypeOf('string');
+ expect(Array.isArray(list.symbols)).toBe(true);
+ }
+ });
+
it('lists private indicators', async () => {
const list = await getPrivateIndicators(auth);
expect(Array.isArray(list)).toBe(true);
diff --git a/tests/live/data.test.ts b/tests/live/data.test.ts
index e6f53da..77d19ed 100644
--- a/tests/live/data.test.ts
+++ b/tests/live/data.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
getCandles, getQuote, getQuotes, getSymbolInfo, getTechnicalAnalysis, searchIndicators, searchMarkets,
- watchCandles, watchQuotes, getIndicatorData,
+ watchCandles, watchQuotes, getIndicatorData, getScreener, getHotlist,
} from '../../src/data/index.js';
import { LIVE, minGap } from './env.js';
@@ -76,3 +76,27 @@ describe.skipIf(!LIVE)('live: high-level data API', () => {
}
});
});
+
+
+describe.skipIf(!LIVE)('live: scanner discovery', () => {
+ it('returns a requested symbol and numeric price columns', async () => {
+ const page = await getScreener({ market: 'crypto', symbols: ['BINANCE:BTCUSDT'], columns: ['close', 'name'] }, {
+ signal: AbortSignal.timeout(15_000),
+ });
+ expect(page.totalCount).toBeGreaterThan(0);
+ expect(page.rows).toEqual([expect.objectContaining({ symbol: 'BINANCE:BTCUSDT', values: {
+ close: expect.any(Number), name: expect.any(String),
+ } })]);
+ });
+
+ it('returns populated ranked stocks without claiming UI parity', async () => {
+ const page = await getHotlist({ kind: 'mostActive', columns: ['volume'], range: [0, 5] }, {
+ signal: AbortSignal.timeout(15_000),
+ });
+ expect(page.rows.length).toBeGreaterThan(0);
+ expect(page.rows.length).toBeLessThanOrEqual(5);
+ const volumes = page.rows.map((row) => row.values.volume);
+ for (const volume of volumes) expect(volume).toBeTypeOf('number');
+ expect(volumes).toEqual([...volumes].sort((a, b) => Number(b) - Number(a)));
+ });
+});
diff --git a/tests/unit/client.test.ts b/tests/unit/client.test.ts
index f5332ad..af047a8 100644
--- a/tests/unit/client.test.ts
+++ b/tests/unit/client.test.ts
@@ -168,3 +168,28 @@ describe('TradingViewClient', () => {
await client.close();
});
});
+
+
+describe('account lookup lifecycle', () => {
+ for (const ending of ['close', 'timeout', 'disconnect'] as const) {
+ it(`aborts pending authentication on ${ending} without a secondary AUTH_ERROR`, async () => {
+ let signal: AbortSignal | undefined;
+ const fetch = (async (_url, init) => {
+ signal = init?.signal ?? undefined;
+ return new Promise<Response>((_resolve, reject) => {
+ signal?.addEventListener('abort', () => reject(signal?.reason), { once: true });
+ });
+ }) as typeof globalThis.fetch;
+ const { server, client } = setup({ credentials: { session: 'fixture' }, fetch, connectTimeoutMs: 20 });
+ const errors: string[] = [];
+ client.on('error', (error) => errors.push(error.code));
+ if (ending === 'close') await client.close();
+ if (ending === 'disconnect') server.last.drop();
+ await expect(client.ready).rejects.toMatchObject({ code: ending === 'timeout' ? 'TIMEOUT' : 'DISCONNECTED' });
+ await until(() => client.isClosed);
+ expect(signal?.aborted).toBe(true);
+ expect(errors).toEqual(ending === 'timeout' ? ['TIMEOUT'] : []);
+ expect(server.last.packets('set_auth_token')).toHaveLength(0);
+ });
+ }
+});
diff --git a/tests/unit/http.test.ts b/tests/unit/http.test.ts
index 914cb9f..b1f5240 100644
--- a/tests/unit/http.test.ts
+++ b/tests/unit/http.test.ts
@@ -318,3 +318,33 @@ describe('PinePermissionManager', () => {
await expect(manager.getUsers()).rejects.toMatchObject({ code: 'HTTP_ERROR', message: 'You are not the owner' });
});
});
+
+
+describe('HTTP response body failures', () => {
+ it('normalizes stream failures after headers have arrived', async () => {
+ const failure = new Error('response stream reset');
+ const fetch = (async () => ({ text: async () => { throw failure; } })) as unknown as typeof globalThis.fetch;
+ await expect(searchMarkets('BTC', { fetch })).rejects.toMatchObject({ code: 'HTTP_ERROR', cause: failure });
+ });
+
+ it('preserves abort classification during response body consumption', async () => {
+ const failure = new DOMException('body cancelled', 'AbortError');
+ const fetch = (async () => ({ text: async () => { throw failure; } })) as unknown as typeof globalThis.fetch;
+ await expect(searchMarkets('BTC', { fetch })).rejects.toMatchObject({ code: 'ABORTED', cause: failure });
+ });
+});
+
+
+describe('account token validation', () => {
+ it('does not authenticate a marker, empty token or rejected HTTP response', async () => {
+ for (const [page, status] of [
+ ['auth_token is unavailable', 200],
+ ['{"auth_token":""}', 200],
+ ['{"auth_token":"unexpected"}', 403],
+ ] as const) {
+ await expect(getUser({ session: 'fixture' }, {
+ fetch: mockFetch(() => new Response(page, { status })).fetch,
+ })).rejects.toMatchObject({ code: 'AUTH_ERROR' });
+ }
+ });
+});
diff --git a/tests/unit/transport.test.ts b/tests/unit/transport.test.ts
new file mode 100644
index 0000000..5faadb9
--- /dev/null
+++ b/tests/unit/transport.test.ts
@@ -0,0 +1,76 @@
+import { spawn } from 'node:child_process';
+import { once } from 'node:events';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+import { wsTransport } from '../../src/client/transport.js';
+import { TradingViewClient } from '../../src/client/client.js';
+
+async function localServer(mode: string) {
+ const child = spawn('node', [fileURLToPath(new URL('../helpers/native-server.mjs', import.meta.url)), mode], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ const exit = once(child, 'exit');
+ const port = await Promise.race([
+ once(child.stdout, 'data').then(([data]) => Number(String(data).trim())),
+ exit.then(() => { throw new Error('Loopback fixture exited before listening'); }),
+ ]);
+ return {
+ url: `ws://127.0.0.1:${port}`,
+ async stop() { child.kill(); await exit; },
+ };
+}
+
+// Real ws clients on Node/Bun against an independent Node loopback fixture.
+describe('native websocket transport', () => {
+ it('sends headers and text, decodes binary messages and reports a remote close', async () => {
+ const server = await localServer('echo');
+ let opened!: () => void;
+ const open = new Promise<void>((resolve) => { opened = resolve; });
+ let received!: (value: string) => void;
+ const message = new Promise<string>((resolve) => { received = resolve; });
+ let closed!: (value: unknown) => void;
+ const close = new Promise((resolve) => { closed = resolve; });
+ const errors: Error[] = [];
+ const transport = wsTransport({ url: server.url, origin: 'https://www.tradingview.com', headers: { 'X-Test': 'native' } }, {
+ onOpen: opened, onMessage: received, onError: (error) => errors.push(error),
+ onClose: (code, reason) => closed({ code, reason }),
+ });
+ try {
+ await open;
+ expect(transport.isOpen).toBe(true);
+ transport.send('Unicode: 日本語');
+ expect(JSON.parse(await message)).toEqual({
+ origin: 'https://www.tradingview.com', header: 'native', echo: 'Unicode: 日本語',
+ });
+ expect(await close).toEqual({ code: 1000, reason: 'finished' });
+ expect(transport.isOpen).toBe(false);
+ transport.close();
+ expect(errors).toEqual([]);
+ } finally {
+ transport.close();
+ await server.stop();
+ }
+ });
+
+ it('propagates a failed native handshake to client readiness and sessions', async () => {
+ const server = await localServer('reject');
+ const client = new TradingViewClient({
+ transport: (request, handlers) => wsTransport({ ...request, url: server.url }, handlers),
+ });
+ const errors: string[] = [];
+ client.on('error', (error) => errors.push(error.code));
+ const close = new Promise<void>((resolve) => { client.on('close', () => resolve()); });
+ let cause: unknown;
+ client.registerSession('test', { onPacket() {}, onClose: (error) => { cause = error.cause; } });
+ try {
+ await expect(client.ready).rejects.toMatchObject({ code: 'CONNECTION_ERROR' });
+ await close;
+ expect(client.isClosed).toBe(true);
+ expect(errors).toEqual(['CONNECTION_ERROR']);
+ expect(cause).toMatchObject({ code: 'CONNECTION_ERROR' });
+ } finally {
+ await client.close();
+ await server.stop();
+ }
+ });
+});
diff --git a/vitest.config.ts b/vitest.config.ts
index fde5f80..e873c80 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -4,5 +4,11 @@ export default defineConfig({
test: {
include: ['tests/unit/**/*.test.ts'],
testTimeout: 5_000,
+ coverage: {
+ provider: 'v8',
+ include: ['src/**/*.ts'],
+ reporter: ['text', 'json-summary', 'html'],
+ thresholds: { lines: 90, statements: 85, functions: 85, branches: 75 },
+ },
},
});