Skip to content

📈 Get real-time stocks from TradingView

Complete V4 reliability tooling and prepare beta.2 (#335)

Mathieu Colmonb6731886f6f2
diff --git a/README.md b/README.md
index 5e6bf75..1da4998 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). 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). 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
diff --git a/docs/protocol-contributing.md b/docs/protocol-contributing.md
new file mode 100644
index 0000000..e5d17ab
--- /dev/null
+++ b/docs/protocol-contributing.md
@@ -0,0 +1,75 @@
+# Extending the TradingView protocol
+
+This guide is for maintainers and coding agents. The protocol is undocumented and
+may change upstream. Start from an observed exchange, not a guessed command name.
+
+## 1. Establish a reproducible case
+
+Record the issue, symbol, timeframe, account plan, study identifier and expected
+behavior. Separate a missing implementation from an entitlement refusal, stale
+cookie, closed market or browser-only feature. Confirm the same operation in the
+matching TradingView account before asserting parity.
+
+For browser captures, keep only the minimal request/response sequence needed to
+explain the behavior. Remove cookies, auth tokens, account identifiers and private
+script source. Never commit a raw authenticated network log.
+
+## 2. Choose the layer
+
+| Concern | Implementation | Regression tests |
+| --- | --- | --- |
+| Frame lengths, heartbeats, packet decoding | `src/protocol/` | `tests/unit/protocol.test.ts` |
+| Socket lifecycle and session routing | `src/client/` | `tests/unit/client.test.ts` |
+| Chart commands, candle state, Replay | `src/chart/chart-session.ts` | `tests/unit/chart.test.ts` |
+| Study updates and graphics | `src/chart/study.ts`, `graphics.ts` | `tests/unit/study.test.ts` |
+| Plain/compressed strategy reports | `src/chart/strategy.ts` | `tests/unit/strategy.test.ts` |
+| HTTP endpoints | `src/http/` | `tests/unit/http.test.ts` |
+| One-shot calls and cancellable watchers | `src/data/` | `tests/unit/data.test.ts` |
+
+Read the closest implementation and test before editing. Preserve the distinction
+between native `BuiltInIndicator` identifiers and Pine identifiers resolved by
+`getIndicator`. A chart session is not the browser's existing chart. Deep
+Backtesting uses a separate history protocol; ordinary strategy reports do not
+prove support for it.
+
+## 3. Make the contract explicit
+
+Define public types, units, ordering and missing-value behavior. Candle timestamps
+are Unix seconds and high-level candles are oldest first. Preserve unknown values
+as unknown instead of converting absence into zero. Keep existing exports and
+cancellation/timeout behavior. HTTP additions use the existing request helper and
+accept injected `fetch` and `signal`; socket additions use existing session routing.
+
+For stateful packets, test initial data, incremental updates, malformed payloads,
+server errors and cleanup. Validate a complete update before mutating state. A
+watcher must stop on cancellation/disconnection and release listeners/sessions.
+Do not promise automatic reconnect: the current client is terminal after close.
+
+## 4. Verify at the right strength
+
+```sh
+npm ci
+npm run check
+npm run test:bun
+npm audit
+```
+
+For upstream behavior, run a small bounded live probe or `npm run test:live`.
+Authenticated tests read `SESSION` and `SIGNATURE` from the environment; do not put
+them in examples, logs or command arguments. Run live tests only with authorized
+accounts/assets. Record the tested symbol, timeframe and account tier, not secrets.
+
+Use `npm run probe:parity` for the documented V3/V4 candle comparison and
+`npm run probe:endurance -- --minutes=2 --cycle-seconds=30` for a short lifecycle
+smoke. See [reliability evidence](v4-reliability.md) for setup and longer probes.
+A rotating-connection run is not a single long-lived connection reproduction;
+a crypto probe cannot establish forex or subscribed-futures parity.
+
+## 5. Deliver without overstating coverage
+
+Update API docs, a runnable example if useful, [coverage](v4-coverage.md) and the
+relevant [backlog disposition](v4-backlog-triage.md). Distinguish mocked regression,
+live observation and unresolved account-specific reports. Include commands and
+results in the PR; inspect all CI jobs, including non-blocking live failures.
+Publish prereleases with `--tag beta` only. Keep `latest` on V3 until a separate
+stable-release decision; a merged PR does not itself publish an npm version.
diff --git a/docs/release-4.0.0-beta.2.md b/docs/release-4.0.0-beta.2.md
new file mode 100644
index 0000000..5d59f56
--- /dev/null
+++ b/docs/release-4.0.0-beta.2.md
@@ -0,0 +1,25 @@
+# 4.0.0-beta.2
+
+Target npm dist-tag: **beta**. Keep **latest** on 3.5.2.
+
+## Changes since beta.1
+
+- Account lookup starts on `/chart/` and follows only HTTP redirects (#321).
+- Market search accepts optional country and sector filters (#225).
+- Regression coverage for empty notification counts (#243).
+- Upgrade development tooling to patched Vitest 4.1.11+; npm audit is clean.
+- Integrate V3/V4 parity and endurance probes and the controlled-disconnection
+ live regression from #330, without its stale release/version changes.
+- Record the completed two-hour rotating-connection run and its limitations.
+- Add a protocol contribution guide and correct prerelease installation guidance
+ in `llms.txt`.
+
+No intended breaking change relative to beta.1. See [migration-v4.md](migration-v4.md)
+for the breaking V3-to-V4 migration and [backlog triage](v4-backlog-triage.md) for
+unresolved private, paid-account and long-duration reports.
+
+## Release checks
+
+Run deterministic Node/Bun suites, typecheck, lint, build, packed-consumer smoke,
+dependency audit and live tests. Publish the inspected tarball only after CI
+passes; verify the registry version, dist-tags and a fresh installation afterward.
diff --git a/docs/v4-backlog-triage.md b/docs/v4-backlog-triage.md
index 4a9ff77..8f40f41 100644
--- a/docs/v4-backlog-triage.md
+++ b/docs/v4-backlog-triage.md
@@ -2,6 +2,8 @@
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.
+
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.
diff --git a/docs/v4-coverage.md b/docs/v4-coverage.md
index 8660335..0f8cede 100644
--- a/docs/v4-coverage.md
+++ b/docs/v4-coverage.md
@@ -1,17 +1,19 @@
# v4 coverage matrix
-[Migration guide](migration-v4.md) · [Data API](data-api.md) · [Low-level API](low-level-api.md)
+[Migration guide](migration-v4.md) · [Data API](data-api.md) · [Low-level API](low-level-api.md) · [Reliability evidence](v4-reliability.md) · [Protocol contribution guide](protocol-contributing.md)
This matrix lists every capability of v3 (`main.js`, `src/`, examples, tests) and of the `agent.ts` preview, with its v4 replacement and the evidence that it works.
**Evidence columns**
-- **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`.
+- **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`.
- **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;
- ➖ not applicable (no network involved).
+Beta.2 follow-up on **3 October 2026**: all 22 current live tests passed locally with the existing account, including the additional controlled-disconnection/replacement-client test. The historical run above remains evidence for the original 21-test suite.
+
Test names are abbreviated as `file › test`.
## Package and tooling
diff --git a/docs/v4-reliability.md b/docs/v4-reliability.md
new file mode 100644
index 0000000..ea8331b
--- /dev/null
+++ b/docs/v4-reliability.md
@@ -0,0 +1,36 @@
+# V4 reliability evidence
+
+This page tracks reproducible release checks beyond the [capability matrix](v4-coverage.md). It is evidence for a beta, not a claim that every TradingView account feature works.
+
+## V3/V4 candle parity
+
+On 2 October 2026, the published `@mathieuc/[email protected]` and V4 `main` (`95b6d0f`) loaded the same `BINANCE:BTCEUR` market. For each of `D` and `60`, the probe compared 19 closed candles out of 20 requested. All 38 matched on timestamp and OHLC. Volumes matched after applying V3's two-decimal rounding; V4 intentionally preserves the server precision. The still-open candle was excluded because it can change between sequential requests.
+
+A repeat against the beta.2 candidate on 3 October 2026 again compared all 38 closed candles with zero mismatches.
+
+Repeat without adding V3 to V4's dependencies:
+
+```sh
+npm ci
+npm install --prefix /tmp/tradingview-v3-baseline --no-save --no-package-lock @mathieuc/[email protected]
+TV_V3_ENTRY=/tmp/tradingview-v3-baseline/node_modules/@mathieuc/tradingview/main.js npm run probe:parity
+```
+
+`probe:parity` exits nonzero on a mismatched closed candle. It needs live network access and is not part of deterministic CI.
+
+## Live connection lifecycle
+
+`tests/live/recovery.test.ts` starts candle and quote watchers on one client, closes the connection while both are active, verifies both stop and report `DISCONNECTED`, then fetches candles with a new client. This is a controlled socket close, not proof of recovery from every network failure. The library does not reconnect a closed `TradingViewClient` automatically; consumers create a new client.
+
+`npm run probe:endurance -- --minutes=120 --cycle-seconds=600` streams one-minute BTCUSDT candles and quotes for two hours, rotates the connection every ten minutes, and emits JSON lines with startup counts, updates, heartbeats and errors. It exits nonzero on a startup failure, an early watcher close or missing data. It never reads or logs account credentials. A one-minute smoke run on 2 October 2026 completed three cycles with 16 candle updates, 18 quote updates, five heartbeats and zero errors. The completed two-hour run on 3 October 2026 recorded 12 successful cycles, 1,721 candle updates, 1,765 quote updates and 719 heartbeats, with zero failures/errors and no interruption. Connections rotated every ten minutes: this is not a two-hour unbroken-socket test and does not close #236 or the 12-hour Pine report #188. The saved JSONL summary was recovered before recording these counts. The probe also accepts `--symbol`, `--timeframe` and `--chart-type` for issue-specific checks. For example, issue #236 can be investigated with `--symbol=OANDA:EURUSD --chart-type=HeikinAshi`, though a closed forex market cannot prove that quote updates remain live.
+
+## Account redirect regression
+
+V4 now starts the account lookup at `/chart/` and follows `Location` only on HTTP 3xx responses. A deterministic test covers HTTP 200 with a misleading `Location` header. This ports the relevant guard from legacy PR #322; it does not claim to solve CAPTCHA/WAF challenges. The authenticated manual CI run passed all 22 live tests after this change. The beta.2 candidate also passed all 22 current live tests locally on 3 October 2026, including the recovered lifecycle regression.
+
+## Remaining beta limitations
+
+- Live checks exercise a small set of symbols, scripts and account rights, not every capability.
+- Basic daily Replay and strategy reports are documented in [v4-coverage.md](v4-coverage.md); this is not proof of Deep Backtesting or universal intraday entitlement.
+- Private/invite-only script cases, subscribed futures parity, owned layouts and long-running Pine failures need matching assets and targeted reproductions. See [backlog triage](v4-backlog-triage.md).
+- Live CI is non-blocking. Review its actual test results, not just the overall workflow conclusion, before release.
diff --git a/llms.txt b/llms.txt
index b5c411e..9605fcd 100644
--- a/llms.txt
+++ b/llms.txt
@@ -3,7 +3,7 @@
# https://www.npmjs.com/package/@mathieuc/tradingview
Independent community library for TradingView market data. Not an official TradingView API.
-Version 4 beta: TypeScript, ESM, Node >= 20 or Bun. Breaking rewrite of v3 (no compatibility layer). Currently available from repository source only; npm still serves v3.
+Version 4 beta: TypeScript, ESM, Node >= 20 or Bun. Breaking rewrite of v3 (no compatibility layer). Install the prerelease with npm install @mathieuc/tradingview@beta; the default latest tag remains v3.
Simple data API (import from '@mathieuc/tradingview/data' or the root entry):
- getCandles({ symbol, timeframe?, count?, from?, to?, chartType?, ... }) -> Candle[] oldest first, time in Unix seconds.
@@ -18,6 +18,6 @@ Simple data API (import from '@mathieuc/tradingview/data' or the root entry):
Low-level API: TradingViewClient, client.createChart() (ChartSession: setMarket, setTimeframe, fetchMore, replay, createStudy), client.createQuoteSession(), PineIndicator, BuiltInIndicator, HTTP functions (loginUser, getUser, getIndicator, getPrivateIndicators, getDrawings, PinePermissionManager).
Pine studies need a TradingView account (session cookies). Built-in studies and candles/quotes work anonymously, with history limits.
-Docs: docs/data-api.md, docs/low-level-api.md, docs/migration-v4.md, docs/v4-coverage.md. Examples: examples/.
+Docs: docs/data-api.md, docs/low-level-api.md, docs/migration-v4.md, docs/v4-coverage.md, docs/v4-reliability.md, docs/protocol-contributing.md. Examples: examples/.
No CLI, MCP server, backtesting engine or hosted trading API is shipped. Do not claim otherwise.
Questions and bugs: https://github.com/Mathieu2301/TradingView-API/issues/new/choose
diff --git a/package-lock.json b/package-lock.json
index debb793..2d7fdf3 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@mathieuc/tradingview",
- "version": "4.0.0-beta.1",
+ "version": "4.0.0-beta.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@mathieuc/tradingview",
- "version": "4.0.0-beta.1",
+ "version": "4.0.0-beta.2",
"license": "ISC",
"dependencies": {
"ws": "^8.18.0"
diff --git a/package.json b/package.json
index 806cca9..f7a4015 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@mathieuc/tradingview",
- "version": "4.0.0-beta.1",
+ "version": "4.0.0-beta.2",
"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",
@@ -34,7 +34,9 @@
"test:live": "vitest run --config vitest.live.config.ts",
"smoke": "node scripts/smoke.mjs",
"check": "npm run typecheck && npm run lint && npm test && npm run build && npm run smoke",
- "prepack": "npm run build"
+ "prepack": "npm run build",
+ "probe:endurance": "npm run build && node scripts/endurance.mjs",
+ "probe:parity": "npm run build && node scripts/parity.mjs"
},
"repository": {
"type": "git",
diff --git a/scripts/endurance.mjs b/scripts/endurance.mjs
new file mode 100644
index 0000000..31dd538
--- /dev/null
+++ b/scripts/endurance.mjs
@@ -0,0 +1,80 @@
+/** Opt-in live endurance probe. No credentials are read or logged. */
+import { TradingViewClient } from '../dist/index.js';
+import { watchCandles, watchQuotes } from '../dist/data/index.js';
+
+const argument = (name, fallback) => {
+ const raw = process.argv.find((value) => value.startsWith(`--${name}=`))?.split('=')[1];
+ const number = raw === undefined ? fallback : Number(raw);
+ if (!Number.isFinite(number) || number <= 0) throw new Error(`--${name} must be positive`);
+ return number;
+};
+
+const textArgument = (name, fallback) => process.argv.find((value) => value.startsWith(`--${name}=`))?.split('=')[1] ?? fallback;
+const minutes = argument('minutes', 120);
+const cycleSeconds = argument('cycle-seconds', 600);
+const symbol = textArgument('symbol', 'BINANCE:BTCUSDT');
+const timeframe = textArgument('timeframe', '1');
+const chartType = textArgument('chart-type', undefined);
+const deadline = Date.now() + minutes * 60_000;
+const metrics = { cycles: 0, starts: 0, failures: 0, candleUpdates: 0, quoteUpdates: 0, heartbeats: 0, errors: [] };
+let interrupted = false;
+for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => { interrupted = true; });
+
+const report = (event, extra = {}) => console.log(JSON.stringify({
+ at: new Date().toISOString(), event, ...extra,
+}));
+
+function waitForCycle(ms, watchers) {
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => resolve('elapsed'), ms);
+ Promise.race(watchers.map((watcher) => watcher.closed)).then(() => {
+ clearTimeout(timer);
+ resolve('closed');
+ });
+ });
+}
+
+const status = setInterval(() => report('status', { ...metrics, errors: metrics.errors.slice(-3) }), 60_000);
+report('start', { minutes, cycleSeconds, symbol, timeframe, chartType });
+try {
+ while (!interrupted && Date.now() < deadline) {
+ metrics.cycles += 1;
+ const client = new TradingViewClient();
+ client.on('heartbeat', () => { metrics.heartbeats += 1; });
+ client.on('error', (error) => metrics.errors.push(error.code));
+ let candles;
+ let quotes;
+ try {
+ candles = await watchCandles({ symbol, timeframe, chartType, count: 5, client }, {
+ onData: () => { metrics.candleUpdates += 1; },
+ onError: (error) => metrics.errors.push(error.code),
+ });
+ quotes = await watchQuotes({ symbols: [symbol], fields: 'price', client }, {
+ onData: () => { metrics.quoteUpdates += 1; },
+ onError: (error) => metrics.errors.push(error.code),
+ });
+ if (candles.latest.length !== 5 || typeof quotes.latest[symbol]?.lp !== 'number') {
+ throw new Error('Initial market snapshots incomplete');
+ }
+ metrics.starts += 1;
+ report('connected', { cycle: metrics.cycles, candles: candles.latest.length, quotePricePresent: true });
+ const duration = Math.min(cycleSeconds * 1000, deadline - Date.now());
+ const outcome = await waitForCycle(duration, [candles, quotes]);
+ if (outcome === 'closed' && !interrupted) throw new Error('Watcher closed before planned rotation');
+ report('rotation', { cycle: metrics.cycles, outcome });
+ } catch (error) {
+ metrics.failures += 1;
+ metrics.errors.push(error?.code ?? error?.message ?? String(error));
+ report('failure', { cycle: metrics.cycles, code: error?.code, message: error?.message });
+ } finally {
+ await Promise.allSettled([candles?.stop(), quotes?.stop()]);
+ await client.close();
+ }
+ if (metrics.failures >= 3) break;
+ if (metrics.failures && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 3_000));
+ }
+} finally {
+ clearInterval(status);
+ report('summary', { ...metrics, errors: metrics.errors.slice(-10), interrupted });
+}
+if (metrics.failures || metrics.starts === 0 || metrics.quoteUpdates === 0 || metrics.candleUpdates === 0) process.exitCode = 1;
diff --git a/scripts/parity.mjs b/scripts/parity.mjs
new file mode 100644
index 0000000..c8adead
--- /dev/null
+++ b/scripts/parity.mjs
@@ -0,0 +1,54 @@
+/** Opt-in live comparison with the published v3 package. */
+import { createRequire } from 'node:module';
+const require = createRequire(import.meta.url);
+const entry = process.env.TV_V3_ENTRY;
+if (!entry) throw new Error('Set TV_V3_ENTRY to the installed v3 main.js path');
+const { Client } = require(entry);
+const { getCandles } = await import('../dist/data/index.js');
+const symbol = 'BINANCE:BTCEUR';
+
+async function legacyCandles(timeframe) {
+ const client = new Client();
+ const chart = new client.Session.Chart();
+ try {
+ return await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('V3 chart timed out')), 20_000);
+ const fail = (...parts) => { clearTimeout(timer); reject(new Error(parts.map(String).join(' '))); };
+ chart.onError(fail);
+ client.onError(fail);
+ chart.onUpdate(() => {
+ if (chart.periods.length < 20) return;
+ clearTimeout(timer);
+ resolve(chart.periods.map(({ time, open, max, min, close, volume }) => ({
+ time, open, high: max, low: min, close, volume,
+ })).sort((a, b) => a.time - b.time));
+ });
+ chart.setMarket(symbol, { timeframe, range: 20 });
+ });
+ } finally {
+ chart.delete();
+ await client.end();
+ }
+}
+
+let total = 0;
+let mismatches = 0;
+for (const timeframe of ['D', '60']) {
+ const oldBars = await legacyCandles(timeframe);
+ const newBars = await getCandles({ symbol, timeframe, count: 20 });
+ // Last bar can change between requests. V3 rounds volume to two decimals.
+ const oldClosed = oldBars.slice(0, -1);
+ const newClosed = newBars.slice(0, -1);
+ const differences = oldClosed.flatMap((bar, index) => {
+ const next = newClosed[index];
+ const comparable = next && { ...next, volume: Math.round(next.volume * 100) / 100 };
+ return JSON.stringify(bar) === JSON.stringify(comparable) ? [] : [index];
+ });
+ if (oldBars.length !== 20 || newBars.length !== 20) differences.push(-1);
+ total += oldClosed.length;
+ mismatches += differences.length;
+ console.log(JSON.stringify({ timeframe, v3Bars: oldBars.length, v4Bars: newBars.length,
+ closedBarsCompared: oldClosed.length, mismatchIndexes: differences }));
+}
+console.log(JSON.stringify({ closedBarsCompared: total, mismatches }));
+if (mismatches) process.exitCode = 1;
diff --git a/tests/live/recovery.test.ts b/tests/live/recovery.test.ts
new file mode 100644
index 0000000..9112ec5
--- /dev/null
+++ b/tests/live/recovery.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+import { TradingViewClient } from '../../src/index.js';
+import { getCandles, watchCandles, watchQuotes, type CandleWatcher, type QuoteWatcher } from '../../src/data/index.js';
+import { LIVE } from './env.js';
+
+describe.skipIf(!LIVE)('live: connection recovery', () => {
+ it('closes active watchers and starts fresh on a new connection', async () => {
+ const symbol = 'BINANCE:BTCUSDT';
+ const client = new TradingViewClient();
+ const errors: string[] = [];
+ let candles: CandleWatcher | undefined;
+ let quotes: QuoteWatcher | undefined;
+ try {
+ candles = await watchCandles({ symbol, timeframe: '1', count: 5, client }, {
+ onData: () => {}, onError: (error) => errors.push(error.code),
+ });
+ quotes = await watchQuotes({ symbols: [symbol], fields: 'price', client }, {
+ onData: () => {}, onError: (error) => errors.push(error.code),
+ });
+ expect(candles.latest).toHaveLength(5);
+ expect(quotes.latest[symbol]?.lp).toBeTypeOf('number');
+ // End the transport while subscriptions are still live, as a lost socket would.
+ await client.close();
+ await Promise.all([candles.closed, quotes.closed]);
+ expect(candles.isActive).toBe(false);
+ expect(quotes.isActive).toBe(false);
+ expect(errors.sort()).toEqual(['DISCONNECTED', 'DISCONNECTED']);
+ } finally {
+ await Promise.allSettled([candles?.stop(), quotes?.stop()]);
+ await client.close();
+ }
+
+ const replacement = new TradingViewClient();
+ try {
+ const resumed = await getCandles({ symbol, timeframe: '1', count: 5, client: replacement });
+ expect(resumed).toHaveLength(5);
+ expect(replacement.isClosed).toBe(false);
+ } finally {
+ await replacement.close();
+ }
+ });
+});