Skip to content

πŸ“ˆ Get real-time stocks from TradingView

26.0 KB
Raw Blame

v4 coverage matrix

Migration guide Β· Data API Β· Low-level API Β· Reliability evidence Β· Protocol contribution guide

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; 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:
    • βœ… 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.

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 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
CommonJS entry require('@mathieuc/tradingview') (main.js) ESM entry @mathieuc/tradingview with .d.ts; require() works on Node β‰₯ 20.19/22.12 (require(esm)) exports β€Ί root entry...; scripts/smoke.mjs (packs the tarball, imports under Node and Bun, require() check, strict TS consumer without @types/node) βž–
agent.js / agent.d.ts preview entry @mathieuc/tradingview/data subpath exports β€Ί data entry only exposes...; smoke test βž–
JSDoc types (src/types.js: Timezone, TimeFrame, MarketSymbol) TypeScript types Timezone, Timeframe, MarketSymbol (src/chart/types.ts) npm run typecheck; smoke consumer βž–
build:agent, lint:agent, prepack scripts build, typecheck, lint, test, test:bun, test:live, smoke, check, prepack CI workflow βž–
CI: Node 14/18/19 live tests on every push + nightly; agent job CI: typecheck, lint, unit tests (Vitest), build and smoke on Node 20/22/24; unit tests with Bun's test runner and smoke on Bun; live tests only nightly/manual, non-blocking .github/workflows/tests.yml βž–
docs/DOCS.md (pointer to JSDoc) docs/data-api.md, docs/low-level-api.md, docs/migration-v4.md, this matrix n/a βž–

Protocol and transport

v3 capability v4 Unit evidence Live
protocol.parseWSPacket (frame split, heartbeat as number, invalid JSON warning) protocol.decodeFrames (length-based, UTF-16 lengths, typed frames, lenient fallback, invalid frames reported) protocol β€Ί decodes several frames..., keeps payloads containing frame markers intact, reports invalid JSON..., falls back to splitting malformed input, decodes every message of a captured live session βœ… (fixture captured live; UTF-16 lengths checked on Japanese/Korean descriptions)
protocol.formatWSPacket protocol.encodeFrame, encodePacket, encodeHeartbeat protocol β€Ί encodes packets with UTF-16 lengths βœ…
protocol.parseCompressed (ZIP via jszip, base64 normalisation, zlib/raw/gzip fallbacks) protocol.decodeCompressed (built-in ZIP reader: stored, deflated, data descriptors, empty entry names; zlib, raw deflate, gzip, plain JSON) and normaliseBase64, readFirstZipEntry protocol β€Ί compressed payloads β€Ί * (ZIP fixtures generated independently with Python zipfile) βœ… private compressed browser capture replayed through compiled parser (3 October 2026); plain report verified
utils.genSessionID protocol.createSessionId (crypto-random) protocol β€Ί ids βž–
utils.genAuthCookies Internal cookie builder used by every HTTP call http β€Ί * with credentials (cookie headers asserted) βž–
Websocket URL wss://<server>.tradingview.com/socket.io/websocket?from=chart&type=chart, Origin and browser headers Same, in TradingViewClient; transport is pluggable (transport option, default ws) client β€Ί connects with browser-like headers... βœ… Node and Bun (Bun needed the Origin header fix)
Heartbeat (~h~) echo, onPing Automatic echo, heartbeat event client β€Ί answers heartbeats... βœ…
protocol_error β†’ error + close PROTOCOL_ERROR error + close client β€Ί turns protocol_error into an error event and closes βœ… (observed during probes)
Send queue until open and authenticated; sendQueue() Automatic queue and flush client β€Ί connects ... then flushes queued packets βœ…
Packet routing to sessions by ID Same (registerSession) client β€Ί routes packets to registered sessions, routes a captured live session... βœ…
global.TW_DEBUG / DEBUG option Per-client `debug: true (...args) => void` client β€Ί logs traffic through a debug function

Client, authentication and events

v3 capability v4 Unit evidence Live
new Client() anonymous (unauthorized_user_token) new TradingViewClient() client β€Ί connects with ... an anonymous token βœ…
token + signature options β†’ getUser β†’ set_auth_token credentials: { session, signature } (and new authToken) client β€Ί loads the auth token from credentials..., uses an explicit auth token βœ… (authenticated β€Ί gets the account, opens an authenticated connection)
location option location client β€Ί loads the auth token... (asserts the regional URL) πŸ”’
server option (data, prodata, widgetdata) server client β€Ί connects with browser-like headers... (prodata URL) βœ… data; πŸ”’ prodata
headers option headers client β€Ί connects with browser-like headers... βœ…
Credentials error reported through onError AUTH_ERROR (rejects ready, error event, connection closed, cause passed to sessions) client β€Ί fails, emits AUTH_ERROR..., rejects ready without logging... βœ… (fake cookie rejected live in examples/errors.js)
onConnected, onDisconnected, onLogged, onPing, onData, onError, onEvent open, close, ready/hello, heartbeat, packet, error events and onAny client β€Ί answers heartbeats and emits hello, heartbeat and unrouted packets, events β€Ί * βœ…
isLogged, isOpen isAuthenticated, isOpen, isClosed, serverInfo client β€Ί connects ... βœ…
client.send(t, p) raw packets client.send(method, params) client β€Ί accepts a raw frame string through send() βœ…
client.end() client.close() (resolves when closed, idempotent, sessions released silently) client β€Ί close() is idempotent..., chart β€Ί intentional close βœ…
Disconnection handling DISCONNECTED to charts, studies, quote subscriptions and pending calls client β€Ί notifies sessions..., chart β€Ί reports DISCONNECTED..., quote β€Ί reports DISCONNECTED..., data β€Ί rejects with DISCONNECTED... βž– (simulated)
(new) Connection timeout connectTimeoutMs, TIMEOUT client β€Ί times out if the connection never opens βž–

Charts

v3 capability v4 Unit evidence Live
new client.Session.Chart() / chart_create_session client.createChart() chart β€Ί creates a session, resolves the symbol... βœ…
setMarket(symbol, { timeframe, range }) setMarket(symbol, { timeframe, count }) chart β€Ί creates a session...; data β€Ί getCandles β€Ί * βœ…
Candles chart.periods (newest first, max/min) chart.candles (oldest first, high/low), lastCandle chart β€Ί creates a session..., parses a captured live chart session βœ…
to reference (['bar_count', to, range]) to option; getCandles({ to }) chart β€Ί encodes market options..., data β€Ί loads a from/to range... βœ… recent past reference with account (authenticated β€Ί uses an account timeframe...); older history remains server-limited
Negative range (bars after to), "fake replay" Negative count + fetchMore(-n) chart β€Ί encodes market options... βœ… (sessions β€Ί loads bars after a past reference..., examples/fake-replay.js)
fetchMore(n) / deep history chart.fetchMore(n); automatic batching in getCandles (count or from), stops on data_completed chart β€Ί fetches more history..., data β€Ί loads deep history in batches..., stops when the server has no more history βœ… (3 000 hourly and 6 600 hourly bars; anonymous cap observed as data_completed: "limit")
(new) From/to date ranges getCandles({ from, to, maxCount }) data β€Ί loads a from/to range... βœ… (from anonymously, recent past to with account)
adjustment (splits/dividends) adjustment chart β€Ί encodes market options... βœ… default; βž– dividends
backadjustment backAdjustment chart β€Ί encodes market options..., data β€Ί passes chart options... βž– (encoding only)
session (regular/extended) session same βž– (encoding only)
currency (currency-id) currency same βž– (encoding only)
Custom chart types: HeikinAshi, Renko, LineBreak, Kagi, PointAndFigure, Range + inputs type + inputs; getCandles({ chartType, chartInputs }) chart β€Ί encodes market options..., modifies the series... βœ… all six (data β€Ί gets custom chart types, examples/custom-chart-types.js)
setSeries(timeframe) setTimeframe(timeframe) chart β€Ί modifies the series on later setMarket/setTimeframe calls... βœ… (D β†’ 15)
setSeries before market β†’ error INVALID_STATE thrown chart β€Ί modifies the series... βœ… (examples/errors.js)
setTimezone(tz) setTimezone(tz); getCandles({ timezone }) chart β€Ί fetches more history and switches timezone βœ…
Custom timeframes (1S, 20...) Any Timeframe string data β€Ί passes chart options... βœ… account timeframe 240; πŸ”’ 1S/20 not exercised
onSymbolLoaded, chart.infos symbolLoaded event, symbolInfo; getSymbolInfo() chart β€Ί creates a session..., data β€Ί getSymbolInfo βœ…
onUpdate(changes) update event chart β€Ί creates a session... βœ…
(new) series_loading / series_completed seriesLoading, seriesCompleted (`dataCompleted: end limit`) chart β€Ί fetches more history...
symbol_error, series_error, critical_error β†’ onError SYMBOL_ERROR, SERIES_ERROR, CRITICAL_ERROR chart β€Ί emits typed errors... βœ… (sessions β€Ί reports server errors as typed errors)
delete() delete() (idempotent; also deletes the replay session) chart β€Ί rejects pending replay requests when deleted... βœ…

Replay

v3 capability v4 Unit evidence Live
setMarket(symbol, { replay }) (replay session, add series, reset) Same option chart β€Ί runs replay mode... βœ…
replayStep(n), replayStart(interval), replayStop() resolved by replay_ok Same; reject with INVALID_STATE outside replay and on delete chart β€Ί runs replay mode..., rejects pending replay requests... βœ… step (sessions β€Ί replays history step by step); βœ… start/stop acknowledgments and advancing bars on Basic (3 October 2026)
onReplayLoaded, onReplayPoint, onReplayResolution, onReplayEnd replayLoaded, replayPoint, replayResolution, replayEnd events chart β€Ί runs replay mode... βœ…
Replay critical_error CRITICAL_ERROR on the chart; pending replay requests rejected (code path shared with chart errors) βž–

Studies, indicators and strategies

v3 capability v4 Unit evidence Live
new chart.Study(indicator) with instance check chart.createStudy(indicator) (INVALID_ARGUMENT otherwise) study β€Ί creates a Pine study..., modifies and removes a study βœ… built-in and public Pine RSI with account
Pine inputs serialisation (text, pineId, pineVersion, { v, f, t }, colours by index) PineIndicator.toStudyInputs() indicators β€Ί serialises inputs for create_study... βœ… public Pine RSI inputs; colour variant unit-tested
study.periods with plot names, plot_N fallback for unnamed/duplicate plots study.values (oldest first) study β€Ί creates a Pine study, names plots..., chart β€Ί parses a captured live chart session βœ… (built-in volume rows)
study.graphic (labels, lines, boxes, tables + cells, polygons, horizLines, horizHists, raw) and graphicsCmds erase/create study.graphics (cells array, raw object) study β€Ί reads graphics commands..., applies erase commands βœ… horizontal histograms (volume profile); πŸ”’ Pine drawings
Bars-back translation of graphic X indexes Same study β€Ί reads graphics commands... βœ…
study.strategyReport (plain data.report and compressed dataCompressed; trades, performance, history, currency, settings) Same study β€Ί decodes plain and compressed strategy reports, reports undecodable strategy reports as PARSE_ERROR βœ… Supertrend strategy report with account; compressed variant also validated using a private browser capture
study.setIndicator() (modify_study) Same study β€Ί modifies and removes a study πŸ”’
study.remove() Same (idempotent) same βœ…
onReady, onUpdate, onError, study_error ready, loading, update, error (STUDY_ERROR, message formatted with server context) study β€Ί formats study errors with their context βœ… (anonymous Pine refusal reported as STUDY_ERROR)
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 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

v3 capability v4 Unit evidence Live
`new client.Session.Quote({ fields: 'all' 'price', customFields })` `client.createQuoteSession({ fields: 'all' 'price'
new quoteSession.Market(symbol, session) quoteSession.subscribe(symbol, { session }) quote β€Ί creates a session... βœ…
Merged quote data, onData, onLoaded, onEvent data (quote, changes), loaded, onAny; subscription.data quote β€Ί creates a session... βœ… (sessions β€Ί streams quotes through a quote session)
Quote symbol errors β†’ onError QUOTE_ERROR quote β€Ί reports symbol errors... βœ…
Removal of symbols nobody listens to Same quote β€Ί reports symbol errors and removes symbols nobody listens to βž–
market.close() (shared per symbol) subscription.close() with correct reference counting (v3 never decreased its count) quote β€Ί shares one server subscription... βž–
quoteSession.delete() Same (idempotent) same βœ…
(new) One-shot and streaming quotes getQuote, getQuotes, watchQuotes data β€Ί quotes β€Ί * βœ…

HTTP: search, technical analysis, accounts, layouts, permissions

v3 capability v4 Unit evidence Live
searchMarketV3(text, filter, offset) (exchange prefix split) searchMarkets(text, { type, offset, exchange }) http β€Ί queries symbol search v3... βœ… (BINANCE:, nasdaq apple β†’ NASDAQ:AAPL)
searchMarket(text, filter) (deprecated v1 endpoint) Replaced by searchMarkets (same results, maintained endpoint) same βœ…
result.getTA() getTechnicalAnalysis(result.id) http β€Ί requests every period and scales ratings βœ…
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; 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)
getDrawings(layout, symbol, credentials, chartID) getDrawings(layoutId, { symbol, chartId, userId, credentials }) http β€Ί lists drawings with merged state πŸ”’
PinePermManager(session, signature, pineId): getUsers, addUser, modifyExpiration, removeUser PinePermissionManager(pineId, { credentials }), same methods http β€Ί PinePermissionManager β€Ί * πŸ”’ (needs an owned invite-only script)
5xx responses throw; HTTP errors HTTP_ERROR (also wraps network failures) http β€Ί throws HTTP_ERROR..., wraps network failures βž–

High-level data API (agent preview)

Preview capability v4 Unit evidence Live
fetchCandles({ symbol, timeframe, limit }), oldest first, high/low getCandles({ symbol, timeframe, count }) (+ deep history, ranges, chart options) data β€Ί getCandles β€Ί * βœ…
watchCandles(query, { onData, onError }), worker.latest, idempotent stop() Same names + closed, isActive, symbolInfo data β€Ί watchCandles β€Ί * βœ…
timeoutMs (15 s default), AbortSignal Same, for every data function data β€Ί times out..., aborts in flight and before starting, stops on abort after start-up βœ…
Cleanup of chart and connection on success, failure, timeout, abort and disconnect Same, plus shared client support data β€Ί returns ... and closes everything, shares a client without closing it, rejects when a provided client is already closed βœ…
Validation before connecting Same (INVALID_ARGUMENT) data β€Ί rejects invalid queries before connecting βž–
MarketDataProvider / TradingViewProvider injection Same provider-neutral candle contract; getCandles(query, provider) and watchCandles(query, handlers, provider), plus shared client and custom clientOptions.transport for TradingView data β€Ί accepts an alternate candle provider...; other data tests use an injected transport βž–

Examples

v3 example v4 example
SimpleChart.js simple-chart.js (βœ… live)
CustomChartType.js custom-chart-types.js (βœ… live)
CustomTimeframe.js custom-timeframe.js (πŸ”’)
Errors.js errors.js (βœ… live for anonymous cases)
FakeReplayMode.js fake-replay.js (βœ… live)
FromToData.js from-to.js (πŸ”’)
GetDrawings.js drawings.js (πŸ”’)
GraphicIndicator.js graphic-indicator.js (πŸ”’)
MultipleSyncFetch.js multiple-indicators.js (πŸ”’)
PinePermManage.js pine-permissions.js (πŸ”’)
ReplayMode.js replay.js (βœ… live without Pine studies)
Search.js search.js (βœ… live)
UserLogin.js user-login.js (πŸ”’)
AllPrivateIndicators.js private-indicators.js (πŸ”’)
BuiltInIndicator.js builtin-indicator.js (βœ… live)
(new) candles.js (βœ…), watch-candles.js, quotes.js, indicator-data.js, quote-session.js

Intentional changes

These v3 behaviours were changed on purpose; none removes a capability.

  • Bars and study rows are oldest first; candles use high/low; volume is no longer rounded to two decimals.
  • setMarket('') throws instead of silently loading BTCEUR; the default timeframe is D instead of 240.
  • setTimezone no longer clears loaded bars (the server does not resend them).
  • Replay methods reject instead of never resolving outside replay mode.
  • Errors are TradingViewError objects instead of string lists; unhandled error events are still printed, except connection failures that already reject client.ready.
  • searchMarket (deprecated v1 endpoint) is folded into searchMarkets.
  • result.getTA() / result.get() methods on search results became plain data plus getTechnicalAnalysis() / getIndicator().

Not verified live for this release

The 21-test manual live workflow verified authenticated connection, account lookup, a public Pine RSI, a Supertrend strategy report, the private-indicators listing endpoint, and recent historical to with an account. It did not verify password login, actual private/invite-only scripts, older history beyond server limits, second-based/custom timeframes, the prodata server, owned layouts/drawings, or Pine permission changes. Those paths have deterministic tests but need the corresponding account assets to verify live. Run SESSION=... SIGNATURE=... npm run test:live to repeat the authenticated subset.

Basic account follow-up β€” 3 October 2026

A fresh authenticated library client loaded BINANCE:BTCEUR daily Replay at a reference 30 days before the probe. Loading returned five bars; three step requests were acknowledged; automatic playback produced advancing bar timestamps; start and stop were both acknowledged. The client was closed after the bounded probe. This verifies the library protocol for that symbol/timeframe/reference, not intraday Replay, every exchange, unlimited history, or simulated order entry. The existing browser chart and its settings were not changed.

examples/strategy-report.js was executed with the same Basic account against the public Supertrend strategy on BINANCE:BTCEUR, timeframe 60, count 300. It returned trade records, closed/open aggregate counts and PnL, and buy-and-hold history. No private payloads or credentials are included in this repository. The strategy may compute over more history than the requested candle count; count is not an exact backtest-window guarantee.

UI CSV and XLSX exports remain plan-blocked (Essential offered), and Deep Backtesting remains plan-blocked (Premium offered). The library report example is not an implementation of those UI exports and does not enable Deep Backtesting.