π Get real-time stocks from TradingView
TypeScript backtestingbacktesting-trading-strategiesbitcoinchartscryptocryptocurrencyethereumrealtime-stocksstocksstocks-apistocks-pricestradingtradingviewtradingview-apitradingview-indicatortradingview-replaytradingview-scraper
Add typed screener API and prepare beta.3 (#336)
Mathieu Colmona21fe9ea2be3
diff --git a/docs/data-api.md b/docs/data-api.mdindex 5d2e8c4..92872a0 100644--- a/docs/data-api.md+++ b/docs/data-api.md@@ -283,3 +283,9 @@ Every failure is a `TradingViewError` with a `code`:| `CALLBACK_ERROR` | A watcher callback threw; the stream remains active. |`error.details` keeps the raw server payload when there is one.++## Screener++Use [`getScreener`](screener.md) for a single scanner page with custom columns,+filters, ranking and explicit pagination. Available from this high-level entry+point as well as the root package; no chart or quote session is required.diff --git a/docs/screener.md b/docs/screener.mdnew file mode 100644index 0000000..5fd49fc--- /dev/null+++ b/docs/screener.md@@ -0,0 +1,42 @@+# Screener++`getScreener` is available from both the root package and `@mathieuc/tradingview/data`.+It performs one HTTP scan, without creating WebSocket sessions.++```js+import { getScreener } from '@mathieuc/tradingview/data';++const page = await getScreener({+ market: 'america',+ columns: ['name', 'close', 'volume', 'Stoch.RSI.D'],+ filter: [{ left: 'type', operation: 'equal', right: 'stock' }],+ sort: { sortBy: 'volume', sortOrder: 'desc' },+ range: [0, 20],+});+console.log(page.totalCount, page.rows);+```++Each row has an exchange-qualified `symbol` and a `values` object keyed by the+requested columns. Values retain their upstream types, including null. Columns+must be nonempty and unique. Unknown fields and invalid server filters throw+`TradingViewError` with code `HTTP_ERROR`; they do not silently become empty results.++The default market is `global`. Other upstream universes include `america`,+`crypto` and `forex`. Exact column names, filter operations and available markets+are controlled by TradingView, not a stable schema owned by this package.+Use `symbols: ['NASDAQ:AAPL']` to restrict the scan to explicit tickers.++`range` is zero-based and end-exclusive, defaulting to `[0, 50]`. Request subsequent+pages explicitly. Rankings can change between requests; pages are not a transactionally+consistent snapshot. There is no automatic unbounded pagination, polling or retry.++The second argument accepts `credentials`, `fetch`, `headers` and `signal`.+Account cookies may be supplied but do not grant paid exchange rights. This is+**not a real-time screener subscription**: delays and entitlements remain upstream.+Use `watchQuotes` separately when you need quote updates for selected symbols.++## Live evidence++On 3 October 2026 an anonymous America scan with stock filters, volume sorting and+`name`, `close`, `volume`, `Stoch.RSI.D` returned a total count and two typed rows.+This establishes the request/response contract, not paid real-time availability.diff --git a/docs/v4-backlog-triage.md b/docs/v4-backlog-triage.mdindex 8f40f41..9290802 100644--- a/docs/v4-backlog-triage.md+++ b/docs/v4-backlog-triage.md@@ -138,3 +138,9 @@ No issues/legacy PRs were closed, and no contributor comments were sent by this- Dependency audit: baseline had two moderate entries for the same Vitest/mocker advisory; patched development dependency in this change.- No new authenticated, private-script, Premium or long-duration claims are made.- No npm publication or promotion of the `latest` tag is part of this change.++## Screener follow-up++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.diff --git a/examples/screener.js b/examples/screener.jsnew file mode 100644index 0000000..beba66b--- /dev/null+++ b/examples/screener.js@@ -0,0 +1,10 @@+import { getScreener } from '@mathieuc/tradingview/data';++const page = await getScreener({+ market: 'america',+ columns: ['name', 'close', 'volume', 'Stoch.RSI.D'],+ filter: [{ left: 'type', operation: 'equal', right: 'stock' }],+ sort: { sortBy: 'volume', sortOrder: 'desc' },+ range: [0, 10],+});+console.table(page.rows.map(({ symbol, values }) => ({ symbol, ...values })));diff --git a/package-lock.json b/package-lock.jsonindex 2d7fdf3..83ba31a 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "@mathieuc/tradingview",- "version": "4.0.0-beta.2",+ "version": "4.0.0-beta.3","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@mathieuc/tradingview",- "version": "4.0.0-beta.2",+ "version": "4.0.0-beta.3","license": "ISC","dependencies": {"ws": "^8.18.0"diff --git a/package.json b/package.jsonindex f7a4015..933750f 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@mathieuc/tradingview",- "version": "4.0.0-beta.2",+ "version": "4.0.0-beta.3","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 6712f56..57b806e 100644--- a/src/data/index.ts+++ b/src/data/index.ts@@ -46,3 +46,5 @@ export type { StrategyReport } from '../chart/strategy.js';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';diff --git a/src/http/index.ts b/src/http/index.tsindex f289c55..ce7458f 100644--- a/src/http/index.ts+++ b/src/http/index.ts@@ -15,3 +15,5 @@ export type {} from './layouts.js';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';diff --git a/src/http/screener.ts b/src/http/screener.tsnew file mode 100644index 0000000..c608baa--- /dev/null+++ b/src/http/screener.ts@@ -0,0 +1,67 @@+import { TradingViewError } from '../errors.js';+import { request, type AuthHttpOptions } from './request.js';++export interface ScreenerFilter {+ left: string;+ operation: string;+ right?: unknown;+}++export interface ScreenerQuery {+ /** Scanner universe, e.g. america, crypto, forex or global. */+ market?: string;+ /** Exact scanner field names, including optional timeframe suffixes. */+ columns: string[];+ filter?: ScreenerFilter[];+ sort?: { sortBy: string; sortOrder: 'asc' | 'desc' };+ /** Zero-based, end-exclusive page range. Defaults to [0, 50]. */+ range?: [number, number];+ /** Optional exchange-qualified symbols. */+ symbols?: string[];+}++export interface ScreenerRow {+ symbol: string;+ /** Values retain upstream types and nulls; keys match requested columns. */+ values: Record<string, unknown>;+}++export interface ScreenerResult {+ totalCount: number;+ rows: ScreenerRow[];+}++/** One scanner page. This does not subscribe to live prices or grant exchange entitlements. */+export async function getScreener(query: ScreenerQuery, options: AuthHttpOptions = {}): Promise<ScreenerResult> {+ const market = query.market ?? 'global';+ const range = query.range ?? [0, 50];+ if (!/^[a-z][a-z0-9_-]*$/i.test(market)+ || !Array.isArray(query.columns) || !query.columns.length+ || query.columns.some((column) => typeof column !== 'string' || !column.trim())+ || new Set(query.columns).size !== query.columns.length+ || range.length !== 2 || !range.every(Number.isSafeInteger) || range[0] < 0 || range[1] <= range[0]) {+ throw new TradingViewError('INVALID_ARGUMENT', 'Invalid screener market, columns or page range');+ }+ const { data, status } = await request(`https://scanner.tradingview.com/${market}/scan`, {+ method: 'POST',+ credentials: options.credentials,+ headers: { origin: 'https://www.tradingview.com' },+ json: {+ columns: query.columns, range, filter: query.filter ?? [], sort: query.sort,+ symbols: query.symbols === undefined ? undefined : { tickers: query.symbols },+ },+ }, options);+ if (status < 200 || status >= 300 || !data || !Number.isSafeInteger(data.totalCount)+ || data.totalCount < 0 || !Array.isArray(data.data)+ || data.data.some((row: any) => !row || typeof row.s !== 'string'+ || !Array.isArray(row.d) || row.d.length !== query.columns.length)) {+ throw new TradingViewError('HTTP_ERROR', `Unexpected screener response (HTTP ${status})`);+ }+ return {+ totalCount: data.totalCount,+ rows: data.data.map((row: { s: string; d: unknown[] }) => ({+ symbol: row.s,+ values: Object.fromEntries(query.columns.map((column, index) => [column, row.d[index]])),+ })),+ };+}diff --git a/tests/unit/exports.test.ts b/tests/unit/exports.test.tsindex 5872e52..f8ddc5d 100644--- a/tests/unit/exports.test.ts+++ b/tests/unit/exports.test.ts@@ -8,7 +8,7 @@ describe('public API', () => {'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',- 'getIndicator', 'getIndicatorData', 'getPrivateIndicators', 'getQuote', 'getQuotes', 'getSymbolInfo',+ 'getIndicator', 'getIndicatorData', 'getPrivateIndicators', 'getQuote', 'getQuotes', 'getScreener', 'getSymbolInfo','getTechnicalAnalysis', 'getUser', 'loginUser', 'mergeStrategyReport', 'parseGraphics', 'parseIndicatorDefinition','parseTrades', 'protocol', 'quoteSymbolKey', 'resolveQuoteFields', 'searchIndicators', 'searchMarkets', 'summarizeStrategyReport','timeframeSeconds', 'toTradingViewError', 'watchCandles', 'watchIndicator', 'watchQuotes', 'wsTransport',@@ -21,7 +21,7 @@ describe('public API', () => {it('data entry only exposes the simplified data API', () => {expect(Object.keys(data).sort()).toEqual([- 'DEFAULT_TIMEOUT_MS', 'TradingViewError', 'TradingViewProvider', 'getCandles', 'getIndicatorData', 'getQuote', 'getQuotes', 'getSymbolInfo',+ 'DEFAULT_TIMEOUT_MS', 'TradingViewError', 'TradingViewProvider', 'getCandles', 'getIndicatorData', 'getQuote', 'getQuotes', 'getScreener', 'getSymbolInfo','getTechnicalAnalysis', 'searchIndicators', 'searchMarkets', 'summarizeStrategyReport', 'watchCandles', 'watchIndicator', 'watchQuotes',]);expect(data.getCandles).toBe(root.getCandles);diff --git a/tests/unit/screener.test.ts b/tests/unit/screener.test.tsnew file mode 100644index 0000000..6c85b9c--- /dev/null+++ b/tests/unit/screener.test.ts@@ -0,0 +1,60 @@+import { describe, expect, it } from 'vitest';+import { getScreener } from '../../src/data/index.js';++const reply = (data: unknown, status = 200) => (async () => new Response(JSON.stringify(data), { status })) as typeof fetch;++describe('getScreener', () => {+ it('forwards filters, sort, auth and cancellation and maps typed cells without coercion', async () => {+ const controller = new AbortController();+ const fetch = (async (url, init) => {+ expect(url).toBe('https://scanner.tradingview.com/america/scan');+ expect(init?.signal).toBe(controller.signal);+ expect(init?.headers).toMatchObject({ cookie: 'sessionid=test;sessionid_sign=signed' });+ expect(JSON.parse(String(init?.body))).toEqual({+ columns: ['close', 'Stoch.RSI.D', 'name'], range: [10, 20],+ filter: [{ left: 'close', operation: 'greater', right: 10 }],+ sort: { sortBy: 'close', sortOrder: 'desc' }, symbols: { tickers: ['NASDAQ:AAPL'] },+ });+ return new Response(JSON.stringify({ totalCount: 100, data: [{ s: 'NASDAQ:AAPL', d: [12, null, 'Apple'] }] }));+ }) as typeof globalThis.fetch;+ expect(await getScreener({+ market: 'america', columns: ['close', 'Stoch.RSI.D', 'name'], range: [10, 20],+ filter: [{ left: 'close', operation: 'greater', right: 10 }],+ sort: { sortBy: 'close', sortOrder: 'desc' }, symbols: ['NASDAQ:AAPL'],+ }, { fetch, signal: controller.signal, credentials: { session: 'test', signature: 'signed' } })).toEqual({+ totalCount: 100, rows: [{ symbol: 'NASDAQ:AAPL', values: { close: 12, 'Stoch.RSI.D': null, name: 'Apple' } }],+ });+ });++ it('accepts an empty page and preserves special column names safely', async () => {+ expect(await getScreener({ columns: ['close'] }, { fetch: reply({ totalCount: 0, data: [] }) }))+ .toEqual({ totalCount: 0, rows: [] });+ const result = await getScreener({ columns: ['__proto__'] }, {+ fetch: reply({ totalCount: 1, data: [{ s: 'X:Y', d: [42] }] }),+ });+ expect(Object.hasOwn(result.rows[0].values, '__proto__')).toBe(true);+ expect(result.rows[0].values.__proto__).toBe(42);+ });++ it('rejects unsafe paths, ambiguous columns and invalid ranges before fetching', async () => {+ for (const query of [+ { market: '../x', columns: ['close'] }, { columns: [] }, { columns: ['close', 'close'] },+ { columns: [''] }, { columns: ['close'], range: [-1, 2] as [number, number] },+ { columns: ['close'], range: [0, 0] as [number, number] },+ { columns: ['close'], range: [0, 1.5] as [number, number] },+ ]) {+ await expect(getScreener(query, { fetch: (async () => { throw new Error('must not fetch'); }) as typeof fetch }))+ .rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });+ }+ });++ it('rejects non-success statuses, scanner errors and malformed row shapes', async () => {+ for (const data of [{ error: 'Unknown field' }, { totalCount: -1, data: [] },+ { totalCount: 1, data: [{ s: 'X:Y', d: [] }] }, { totalCount: 1, data: [null] }]) {+ await expect(getScreener({ columns: ['close'] }, { fetch: reply(data) }))+ .rejects.toMatchObject({ code: 'HTTP_ERROR' });+ }+ await expect(getScreener({ columns: ['close'] }, { fetch: reply({ totalCount: 0, data: [] }, 429) }))+ .rejects.toMatchObject({ code: 'HTTP_ERROR' });+ });+});