π Get real-time stocks from TradingView
TypeScript backtestingbacktesting-trading-strategiesbitcoinchartscryptocryptocurrencyethereumrealtime-stocksstocksstocks-apistocks-pricestradingtradingviewtradingview-apitradingview-indicatortradingview-replaytradingview-scraper
Add watchlists and scanner-ranked hotlists for beta.4 (#337)
Mathieu Colmone0b6a79a180d
diff --git a/docs/data-api.md b/docs/data-api.mdindex 92872a0..ddc5f5e 100644--- a/docs/data-api.md+++ b/docs/data-api.md@@ -289,3 +289,8 @@ Every failure is a `TradingViewError` with a `code`:Use [`getScreener`](screener.md) for a single scanner page with custom columns,filters, ranking and explicit pagination. Available from this high-level entrypoint as well as the root package; no chart or quote session is required.++## Watchlists and rankings++[`getWatchlists` and `getHotlist`](watchlists.md) provide read-only account lists+and scanner-based gainers, losers and volume rankings. Available from both entry points.diff --git a/docs/v4-backlog-triage.md b/docs/v4-backlog-triage.mdindex 9290802..e2569ae 100644--- a/docs/v4-backlog-triage.md+++ b/docs/v4-backlog-triage.md@@ -144,3 +144,9 @@ No issues/legacy PRs were closed, and no contributor comments were sent by thisBeta.3 adds `getScreener` for #53 and scanner fields relevant to #280. See[screener documentation](screener.md). #85 real-time exchange entitlement is notresolved by a successful HTTP scan. Watchlists and paid/private cases remain open.++## Watchlist follow-up++Beta.4 adds read-only `getWatchlists` and scanner-ranked `getHotlist` (#87).+Authenticated discovery returned two empty lists; populated entries are fixture-tested.+Exact TradingView UI hotlist parity is not claimed. See [watchlists](watchlists.md).diff --git a/docs/watchlists.md b/docs/watchlists.mdnew file mode 100644index 0000000..8af5c9f--- /dev/null+++ b/docs/watchlists.md@@ -0,0 +1,56 @@+# Watchlists and ranked lists++## Read your watchlists++```js+import { getWatchlists } from '@mathieuc/tradingview/data';++const lists = await getWatchlists({+ credentials: {+ session: process.env.TV_SESSION,+ signature: process.env.TV_SIGNATURE,+ },+});+for (const list of lists) console.log(list.id, list.name, list.symbols);+```++This is a read-only account API. Each list preserves its numeric ID, name, ordered+`symbols` and additional upstream metadata. Entries can include section markers;+do not blindly pass every entry to `getQuotes`. Filter for exchange-qualified+symbols appropriate to your application. No lists are created, edited or deleted.++Credentials are required. Access rejection (401/403 or login redirects) produces+`AUTH_ERROR`; malformed responses and other failed statuses produce `HTTP_ERROR`.+Authenticated redirects are not followed. The options also accept `fetch`,+`headers` and `signal`. Treat returned names/symbols as private account data.++## Scanner-ranked lists++```js+import { getHotlist } from '@mathieuc/tradingview/data';++const page = await getHotlist({ kind: 'gainers', range: [0, 10] });+console.log(page.rows);+```++| Kind | Ranking |+| --- | --- |+| `gainers` | Percentage change descending |+| `losers` | Percentage change ascending |+| `mostActive` | Volume descending |+| `volumeGainers` | Relative volume (`relative_volume_10d_calc`) descending |++These are convenient [screener](screener.md) queries, **not an exact replica of the+TradingView hotlist widget**. UI universe, session and liquidity filters may differ.+Default universe: America stocks; default fields: name, close, change, volume and+relative volume. Override `market`, `columns`, `filter`, `range` or `symbols` as+needed. For a non-stock universe, supply appropriate filters (or `filter: []`),+since changing the market does not remove the default stock filter. Exchange data+may be delayed. No automatic polling or paid entitlement is implied.++## Evidence and limits++On 3 October 2026, the account endpoint returned two watchlists successfully.+Both were empty, so nonempty ordered entries and section preservation are covered+by deterministic fixtures, not claimed as live-tested account content. An anonymous+America relative-volume scan returned populated rows. No account data was modified.diff --git a/package-lock.json b/package-lock.jsonindex 83ba31a..d076d61 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "@mathieuc/tradingview",- "version": "4.0.0-beta.3",+ "version": "4.0.0-beta.4","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@mathieuc/tradingview",- "version": "4.0.0-beta.3",+ "version": "4.0.0-beta.4","license": "ISC","dependencies": {"ws": "^8.18.0"diff --git a/package.json b/package.jsonindex 933750f..a3c1bfc 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@mathieuc/tradingview",- "version": "4.0.0-beta.3",+ "version": "4.0.0-beta.4","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",diff --git a/src/data/index.ts b/src/data/index.tsindex 57b806e..7d8515a 100644--- a/src/data/index.ts+++ b/src/data/index.ts@@ -48,3 +48,5 @@ export { summarizeStrategyReport } from '../chart/strategy.js';export type { StrategySummary } from '../chart/strategy.js';export { getScreener } from '../http/screener.js';export type { ScreenerFilter, ScreenerQuery, ScreenerResult, ScreenerRow } from '../http/screener.js';+export { getWatchlists, getHotlist } from '../http/watchlists.js';+export type { Watchlist, WatchlistOptions, HotlistKind, HotlistQuery } from '../http/watchlists.js';diff --git a/src/http/index.ts b/src/http/index.tsindex ce7458f..dcb8e57 100644--- a/src/http/index.ts+++ b/src/http/index.ts@@ -17,3 +17,5 @@ export { PinePermissionManager } from './pine-permissions.js';export type { AuthorizedUser, AuthorizedUserOrder, PinePermissionOptions } from './pine-permissions.js';export { getScreener } from './screener.js';export type { ScreenerFilter, ScreenerQuery, ScreenerResult, ScreenerRow } from './screener.js';+export { getWatchlists, getHotlist } from './watchlists.js';+export type { Watchlist, WatchlistOptions, HotlistKind, HotlistQuery } from './watchlists.js';diff --git a/src/http/watchlists.ts b/src/http/watchlists.tsnew file mode 100644index 0000000..7fc636b--- /dev/null+++ b/src/http/watchlists.ts@@ -0,0 +1,63 @@+import { TradingViewError } from '../errors.js';+import { request, type Credentials, type HttpOptions } from './request.js';+import { getScreener, type ScreenerQuery, type ScreenerResult } from './screener.js';++export interface Watchlist {+ id: number;+ name: string;+ /** Ordered upstream entries, including any section markers. */+ symbols: string[];+ /** Additional upstream metadata, preserved without coercion. */+ [key: string]: unknown;+}++export interface WatchlistOptions extends HttpOptions {+ credentials: Credentials;+}++/** Reads all watchlists belonging to the authenticated account. Never modifies them. */+export async function getWatchlists(options: WatchlistOptions): Promise<Watchlist[]> {+ if (!options?.credentials?.session) {+ throw new TradingViewError('INVALID_ARGUMENT', 'getWatchlists requires account credentials');+ }+ const { data, status } = await request('https://www.tradingview.com/api/v1/symbols_list/all/', {+ credentials: options.credentials,+ headers: { origin: 'https://www.tradingview.com' },+ redirect: 'manual',+ }, options);+ if (status === 401 || status === 403 || (status >= 300 && status < 400)) {+ throw new TradingViewError('AUTH_ERROR', `Watchlist access rejected (HTTP ${status})`);+ }+ if (status < 200 || status >= 300 || !Array.isArray(data)+ || data.some((list: any) => !list || !Number.isSafeInteger(list.id) || typeof list.name !== 'string'+ || !Array.isArray(list.symbols) || list.symbols.some((symbol: unknown) => typeof symbol !== 'string'))) {+ throw new TradingViewError('HTTP_ERROR', `Unexpected watchlist response (HTTP ${status})`);+ }+ return data;+}++export type HotlistKind = 'gainers' | 'losers' | 'mostActive' | 'volumeGainers';+export interface HotlistQuery extends Omit<ScreenerQuery, 'columns' | 'sort'> {+ kind: HotlistKind;+ columns?: string[];+}++/** Scanner-ranked lists, not a promise of parity with the TradingView UI hotlist widget. */+export async function getHotlist(query: HotlistQuery, options: HttpOptions = {}): Promise<ScreenerResult> {+ const rankings = {+ gainers: { sortBy: 'change', sortOrder: 'desc' },+ losers: { sortBy: 'change', sortOrder: 'asc' },+ mostActive: { sortBy: 'volume', sortOrder: 'desc' },+ volumeGainers: { sortBy: 'relative_volume_10d_calc', sortOrder: 'desc' },+ } as const;+ if (!Object.hasOwn(rankings, query.kind)) {+ throw new TradingViewError('INVALID_ARGUMENT', 'Unknown hotlist kind');+ }+ return getScreener({+ ...query,+ market: query.market ?? 'america',+ columns: query.columns ?? ['name', 'close', 'change', 'volume', 'relative_volume_10d_calc'],+ filter: query.filter ?? [{ left: 'type', operation: 'equal', right: 'stock' }],+ sort: rankings[query.kind],+ }, options);+}diff --git a/tests/unit/exports.test.ts b/tests/unit/exports.test.tsindex f8ddc5d..037f130 100644--- a/tests/unit/exports.test.ts+++ b/tests/unit/exports.test.ts@@ -7,9 +7,9 @@ describe('public API', () => {expect(Object.keys(root).sort()).toEqual(['ALL_QUOTE_FIELDS', 'BuiltInIndicator', 'CHART_TYPE_STUDIES', 'ChartSession', 'DEFAULT_TIMEOUT_MS', 'Emitter','PineIndicator', 'PinePermissionManager', 'QuoteSession', 'QuoteSubscription', 'Study', 'TradingViewClient',- 'TradingViewError', 'TradingViewProvider', 'applyGraphicsCommands', 'clearIndicatorCache', 'getCandles', 'getChartToken', 'getDrawings',+ 'TradingViewError', 'TradingViewProvider', 'applyGraphicsCommands', 'clearIndicatorCache', 'getCandles', 'getChartToken', 'getDrawings', 'getHotlist','getIndicator', 'getIndicatorData', 'getPrivateIndicators', 'getQuote', 'getQuotes', 'getScreener', 'getSymbolInfo',- 'getTechnicalAnalysis', 'getUser', 'loginUser', 'mergeStrategyReport', 'parseGraphics', 'parseIndicatorDefinition',+ 'getTechnicalAnalysis', 'getUser', 'getWatchlists', 'loginUser', 'mergeStrategyReport', 'parseGraphics', 'parseIndicatorDefinition','parseTrades', 'protocol', 'quoteSymbolKey', 'resolveQuoteFields', 'searchIndicators', 'searchMarkets', 'summarizeStrategyReport','timeframeSeconds', 'toTradingViewError', 'watchCandles', 'watchIndicator', 'watchQuotes', 'wsTransport',]);@@ -21,8 +21,8 @@ describe('public API', () => {it('data entry only exposes the simplified data API', () => {expect(Object.keys(data).sort()).toEqual([- 'DEFAULT_TIMEOUT_MS', 'TradingViewError', 'TradingViewProvider', 'getCandles', 'getIndicatorData', 'getQuote', 'getQuotes', 'getScreener', 'getSymbolInfo',- 'getTechnicalAnalysis', 'searchIndicators', 'searchMarkets', 'summarizeStrategyReport', 'watchCandles', 'watchIndicator', 'watchQuotes',+ 'DEFAULT_TIMEOUT_MS', 'TradingViewError', 'TradingViewProvider', 'getCandles', 'getHotlist', 'getIndicatorData', 'getQuote', 'getQuotes', 'getScreener', 'getSymbolInfo',+ 'getTechnicalAnalysis', 'getWatchlists', 'searchIndicators', 'searchMarkets', 'summarizeStrategyReport', 'watchCandles', 'watchIndicator', 'watchQuotes',]);expect(data.getCandles).toBe(root.getCandles);});diff --git a/tests/unit/watchlists.test.ts b/tests/unit/watchlists.test.tsnew file mode 100644index 0000000..11f5282--- /dev/null+++ b/tests/unit/watchlists.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it } from 'vitest';+import { getWatchlists, getHotlist } from '../../src/data/index.js';++const credentials = { session: 'fixture', signature: 'signed' };+const reply = (data: unknown, status = 200) => (async () => new Response(JSON.stringify(data), { status })) as typeof fetch;++describe('getWatchlists', () => {+ it('reads ordered entries and metadata without following authenticated redirects', async () => {+ const lists = [{ id: 1, name: 'Example', symbols: ['###Section', 'NASDAQ:AAPL', 'BINANCE:BTCUSDT'], active: true }];+ const controller = new AbortController();+ const fetch = (async (url, init) => {+ expect(url).toBe('https://www.tradingview.com/api/v1/symbols_list/all/');+ expect(init?.redirect).toBe('manual');+ expect(init?.method).toBe('GET');+ expect(init?.signal).toBe(controller.signal);+ expect(init?.headers).toMatchObject({ cookie: 'sessionid=fixture;sessionid_sign=signed' });+ return new Response(JSON.stringify(lists));+ }) as typeof globalThis.fetch;+ expect(await getWatchlists({ credentials, fetch, signal: controller.signal })).toEqual(lists);+ });+ it('supports empty lists and rejects missing credentials', async () => {+ expect(await getWatchlists({ credentials, fetch: reply([]) })).toEqual([]);+ await expect(getWatchlists({ credentials: { session: '' } })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });+ });+ it('distinguishes access rejection from malformed data', async () => {+ for (const status of [301, 302, 401, 403]) {+ await expect(getWatchlists({ credentials, fetch: reply({}, status) })).rejects.toMatchObject({ code: 'AUTH_ERROR' });+ }+ for (const data of [{}, [null], [{ id: 1, name: 'x', symbols: [42] }]]) {+ await expect(getWatchlists({ credentials, fetch: reply(data) })).rejects.toMatchObject({ code: 'HTTP_ERROR' });+ }+ await expect(getWatchlists({ credentials, fetch: reply([], 429) })).rejects.toMatchObject({ code: 'HTTP_ERROR' });+ });+});++describe('getHotlist', () => {+ it('ranks the requested universe and preserves explicit filters and page ranges', async () => {+ for (const [kind, sortBy, sortOrder] of [+ ['gainers', 'change', 'desc'], ['losers', 'change', 'asc'],+ ['mostActive', 'volume', 'desc'], ['volumeGainers', 'relative_volume_10d_calc', 'desc'],+ ] as const) {+ const fetch = (async (url, init) => {+ expect(url).toBe('https://scanner.tradingview.com/crypto/scan');+ expect(JSON.parse(String(init?.body))).toMatchObject({+ columns: ['close'], sort: { sortBy, sortOrder }, filter: [], range: [5, 10],+ });+ return new Response(JSON.stringify({ totalCount: 0, data: [] }));+ }) as typeof globalThis.fetch;+ await getHotlist({ kind, market: 'crypto', columns: ['close'], filter: [], range: [5, 10] }, { fetch });+ }+ });+ it('defaults to America stocks and rejects unknown ranking kinds', async () => {+ const fetch = (async (url, init) => {+ expect(url).toBe('https://scanner.tradingview.com/america/scan');+ expect(JSON.parse(String(init?.body)).filter).toEqual([{ left: 'type', operation: 'equal', right: 'stock' }]);+ return new Response(JSON.stringify({ totalCount: 0, data: [] }));+ }) as typeof globalThis.fetch;+ await getHotlist({ kind: 'gainers' }, { fetch });+ await expect(getHotlist({ kind: 'unknown' as 'gainers' }, { fetch })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });+ });+});