📈 Get real-time stocks from TradingView
TypeScript backtestingbacktesting-trading-strategiesbitcoinchartscryptocryptocurrencyethereumrealtime-stocksstocksstocks-apistocks-pricestradingtradingviewtradingview-apitradingview-indicatortradingview-replaytradingview-scraper
Add examples + Series bug fix
Mathieu Colmon7d33cabf4660
diff --git a/examples/AllPrivateIndicators.js b/examples/AllPrivateIndicators.jsnew file mode 100644index 0000000..a7cca85--- /dev/null+++ b/examples/AllPrivateIndicators.js@@ -0,0 +1,35 @@+const TradingView = require('../main');++/*+ This example creates a chart with+ all user's private indicators+*/++const client = new TradingView.Client({+ /* Token is only needed if at least one indicator is+ PRIVATE (if you have a paid TradingView account) */+ token: 'YOUR_SESSION_ID_COOKIE',+});++const chart = new client.Session.Chart();+chart.setMarket('BINANCE:BTCEUR', {+ timeframe: 'D',+});++TradingView.getPrivateIndicators('YOUR_SESSION_ID_COOKIE').then((indicList) => {+ indicList.forEach(async (indic) => {+ const privateIndic = await indic.get();+ console.log('Loading indicator', indic.name, '...');++ const indicator = new chart.Study(privateIndic);++ indicator.onReady(() => {+ console.log('Indicator', indic.name, 'loaded !');+ });++ indicator.onUpdate(() => {+ console.log('Plot values', indicator.periods);+ console.log('Strategy report', indicator.strategyReport);+ });+ });+});diff --git a/examples/Errors.js b/examples/Errors.jsnew file mode 100644index 0000000..9b9bdd2--- /dev/null+++ b/examples/Errors.js@@ -0,0 +1,153 @@+const TradingView = require('../main');++/*+ This example tests many types of errors+*/++const client = new TradingView.Client(); // Creates a websocket client++const tests = [+ (next) => { /* Testing "Credentials error" */+ console.info('\nTesting "Credentials error" error:');++ const client2 = new TradingView.Client({+ token: 'FAKE_CREDENTIALS', // Set wrong credentials+ });++ client2.onError((...err) => {+ console.error(' => Client error:', err);+ client2.end();+ next();+ });+ },++ (next) => { /* Testing "Invalid symbol" */+ console.info('\nTesting "Invalid symbol" error:');++ const chart = new client.Session.Chart();+ chart.onError((...err) => { // Listen for errors+ console.error(' => Chart error:', err);+ chart.delete();+ next();+ });++ chart.setMarket('XXXXX'); // Set a wrong market+ },++ (next) => { /* Testing "Invalid timezone" */+ console.info('\nTesting "Invalid timezone" error:');++ const chart = new client.Session.Chart();+ chart.onError((...err) => { // Listen for errors+ console.error(' => Chart error:', err);+ next();+ });++ chart.setMarket('BINANCE:BTCEUR'); // Set a market+ chart.setTimezone('Nowhere/Nowhere'); // Set a fake timezone+ },++ (next) => { /* Testing "Custom timeframe" */+ console.info('\nTesting "Custom timeframe" error:');++ const chart = new client.Session.Chart();+ chart.onError((...err) => { // Listen for errors+ console.error(' => Chart error:', err);+ chart.delete();+ next();+ });++ chart.setMarket('BINANCE:BTCEUR', { // Set a market+ timeframe: '20', // Set a custom timeframe+ /*+ Timeframe '20' isn't available because we are+ not logged in as a premium TradingView user+ */+ });+ },++ (next) => { /* Testing "Invalid timeframe" */+ console.info('\nTesting "Invalid timeframe" error:');++ const chart = new client.Session.Chart();+ chart.onError((...err) => { // Listen for errors+ console.error(' => Chart error:', err);+ next();+ });++ chart.setMarket('BINANCE:BTCEUR', { // Set a market+ timeframe: 'XX', // Set a wrong timeframe+ });+ },++ (next) => { /* Testing "Study not auth" */+ console.info('\nTesting "Study not auth" error:');++ const chart = new client.Session.Chart();+ chart.onError((...err) => { // Listen for errors+ console.error(' => Chart error:', err);+ next();+ });++ chart.setMarket('BINANCE:BTCEUR', { // Set a market+ timeframe: '15',+ type: 'Renko',+ });++ chart.onUpdate(() => {+ console.log('DATA', chart.periods[0]);+ });+ },++ (next) => { /* Testing "Set the market before" */+ console.info('\nTesting "Set the market before..." error:');++ const chart = new client.Session.Chart();+ chart.onError((...err) => { // Listen for errors+ console.error(' => Chart error:', err);+ chart.delete();+ next();+ });++ chart.setSeries('15'); // Set series before setting the market+ },++ (next) => { /* Testing "Inexistent indicator" */+ console.info('\nTesting "Inexistent indicator" error:');++ TradingView.getIndicator('STD;XXXXXXX')+ .catch((err) => {+ console.error(' => API error:', [err.message]);+ next();+ });+ },++ async (next) => { /* Testing "Invalid value" */+ console.info('\nTesting "Invalid value" error:');++ const chart = new client.Session.Chart();+ chart.setMarket('BINANCE:BTCEUR'); // Set a market++ const ST = await TradingView.getIndicator('STD;Supertrend');+ ST.setOption('Factor', -1); // This will cause an error++ const Supertrend = new chart.Study(ST);+ Supertrend.onError((...err) => {+ console.error(' => Study error:', err);+ chart.delete();+ next();+ });+ },+];++let i = 0;+const execTest = () => {+ if (tests[i + 1]) {+ tests[(i += 1) - 1](execTest);+ } else {+ tests[(i += 1) - 1](() => {+ console.log(`\nTests ${i}/${i} done !`);+ });+ }+};+execTest();diff --git a/examples/SimpleChart.js b/examples/SimpleChart.jsnew file mode 100644index 0000000..26d15e6--- /dev/null+++ b/examples/SimpleChart.js@@ -0,0 +1,63 @@+const TradingView = require('../main');++/*+ This example creates a BTCEUR daily chart+*/++const client = new TradingView.Client(); // Creates a websocket client++const chart = new client.Session.Chart(); // Init a Chart session++chart.setMarket('BINANCE:BTCEUR', { // Set the market+ timeframe: 'D',+});++chart.onError((...err) => { // Listen for errors (can avoid crash)+ console.error('Chart error:', ...err);+ // Do something...+});++chart.onSymbolLoaded(() => { // When the symbol is successfully loaded+ console.log(`Market "${chart.infos.description}" loaded !`);+});++chart.onUpdate(() => { // When price changes+ if (!chart.periods[0]) return;+ console.log(`[${chart.infos.description}]: ${chart.periods[0].close} ${chart.infos.currency_id}`);+ // Do something...+});++// Wait 5 seconds and set the market to BINANCE:ETHEUR+setTimeout(() => {+ console.log('\nSetting market to BINANCE:ETHEUR...');+ chart.setMarket('BINANCE:ETHEUR', {+ timeframe: 'D',+ });+}, 5000);++// Wait 10 seconds and set the timeframe to 15 minutes+setTimeout(() => {+ console.log('\nSetting timeframe to 15 minutes...');+ chart.setSeries('15');+}, 10000);++// Wait 15 seconds and set the chart type to "Heikin Ashi"+setTimeout(() => {+ console.log('\nSetting the chart type to "Heikin Ashi"s...');+ chart.setMarket('BINANCE:ETHEUR', {+ timeframe: 'D',+ type: 'HeikinAshi',+ });+}, 15000);++// Wait 20 seconds and close the chart+setTimeout(() => {+ console.log('\nClosing the chart...');+ chart.delete();+}, 20000);++// Wait 25 seconds and close the client+setTimeout(() => {+ console.log('\nClosing the client...');+ client.end();+}, 25000);diff --git a/src/chart/session.js b/src/chart/session.jsindex c1669a5..fa7b23b 100644--- a/src/chart/session.js+++ b/src/chart/session.js@@ -3,7 +3,8 @@ const { genSessionID } = require('../utils');const studyConstructor = require('./study');/**- * @typedef {'HeikinAshi' | 'Renko' | 'LineBreak' | 'Kagi'} ChartType Custom chart type+ * @typedef {'HeikinAshi' | 'Renko' | 'LineBreak' | 'Kagi' | 'PointAndFigure'+ * | 'Range'} ChartType Custom chart type*/const ChartTypes = {@@ -63,7 +64,7 @@ const ChartTypes = {* @prop {string} session-display Session display (ex: '24x7')** @typedef {Object} MarketInfos- * @prop {string} series_id Used series (ex: 'sds_sym_1')+ * @prop {string} series_id Used series (ex: 'ser_1')* @prop {string} base_currency Base currency (ex: 'BTC')* @prop {string} base_currency_id Base currency ID (ex: 'XTVCBTC')* @prop {string} name Market short name (ex: 'BTCEUR')@@ -129,6 +130,17 @@ module.exports = (client) => class ChartSession {return Object.values(this.#periods).sort((a, b) => b.time - a.time);}+ /**+ * Current market infos+ * @type {MarketInfos}+ */+ #infos = {};++ /** @return {MarketInfos} Current market infos */+ get infos() {+ return this.#infos;+ }+#callbacks = {seriesLoaded: [],symbolLoaded: [],@@ -156,7 +168,7 @@ module.exports = (client) => class ChartSession {this.#client.sessions[this.#sessionID] = {type: 'chart',onData: (packet) => {- console.log('§90§30§106 CHART SESSION §0 DATA', packet);+ if (global.TW_DEBUG) console.log('§90§30§106 CHART SESSION §0 DATA', packet);if (typeof packet.data[1] === 'string' && this.#studyListeners[packet.data[1]]) {this.#studyListeners[packet.data[1]](packet);@@ -164,10 +176,12 @@ module.exports = (client) => class ChartSession {}if (packet.type === 'symbol_resolved') {- this.#handleEvent('symbolLoaded', {+ this.#infos = {series_id: packet.data[1],...packet.data[2],- });+ };++ this.#handleEvent('symbolLoaded');return;}@@ -204,7 +218,7 @@ module.exports = (client) => class ChartSession {}if (packet.type === 'series_error') {- this.#handleError('Series error:', packet.data);+ this.#handleError('Series error:', packet.data[3]);return;}@@ -218,37 +232,45 @@ module.exports = (client) => class ChartSession {this.#client.send('chart_create_session', [this.#sessionID]);}- #series = []+ #seriesCreated = false;++ #currentSeries = 0;/*** @param {import('../types').TimeFrame} timeframe Chart period timeframe* @param {number} [range] Number of loaded periods/candles (Default: 100)- * @param {string} [ID] Series ID (Default: 'sds_sym_1')*/- setSeries(timeframe = '240', range = 100, ID = 'sds_sym_1') {+ setSeries(timeframe = '240', range = 100) {+ if (!this.#currentSeries) {+ this.#handleError('Please set the market before setting series');+ return;+ }+this.#periods = {};- this.#client.send(`${this.#series.includes(ID) ? 'modify' : 'create'}_series`, [++ this.#client.send(`${this.#seriesCreated ? 'modify' : 'create'}_series`, [this.#sessionID,'$prices','s1',- ID,+ `ser_${this.#currentSeries}`,timeframe,- !this.#series.includes(ID) ? range : '',+ !this.#seriesCreated ? range : '',]);- if (!this.#series.includes(ID)) this.#series.push(ID);+ this.#seriesCreated = true;}/*** Set the chart market* @param {string} symbol Market symbol* @param {Object} [options] Chart options+ * @param {import('../types').TimeFrame} [options.timeframe] Chart period timeframe+ * @param {number} [options.range] Number of loaded periods/candles (Default: 100)* @param {'splits' | 'dividends'} [options.adjustment] Market adjustment* @param {'regular' | 'extended'} [options.session] Chart session* @param {'EUR' | 'USD' | string} [options.currency] Chart currency* @param {ChartType} [options.type] Chart custom type* @param {ChartInputs} [options.inputs] Chart custom inputs- * @param {string} [options.series] Series ID (Default: 'sds_sym_1')*/setMarket(symbol, options = {}) {this.#periods = {};@@ -256,9 +278,10 @@ module.exports = (client) => class ChartSession {const symbolInit = {symbol: symbol || 'BTCEUR',adjustment: options.adjustment || 'splits',- session: options.session || 'regular',};+ if (options.session) symbolInit.session = options.session;+if (options.currency) symbolInit['currency-id'] = options.currency;const chartInit = (options.type && ChartTypes[options.type]) ? {} : symbolInit;@@ -269,11 +292,15 @@ module.exports = (client) => class ChartSession {chartInit.inputs = { ...options.inputs };}+ this.#currentSeries += 1;+this.#client.send('resolve_symbol', [this.#sessionID,- options.series || 'sds_sym_1',+ `ser_${this.#currentSeries}`,`=${JSON.stringify(chartInit)}`,]);++ this.setSeries(options.timeframe, options.range);}/**@@ -295,7 +322,7 @@ module.exports = (client) => class ChartSession {/*** When a symbol is loaded- * @param {(marketInfos: MarketInfos) => void} cb+ * @param {() => void} cb* @event*/onSymbolLoaded(cb) {diff --git a/src/chart/study.js b/src/chart/study.jsindex 510d7bd..1dc55aa 100644--- a/src/chart/study.js+++ b/src/chart/study.js@@ -173,7 +173,7 @@ module.exports = (chartSession) => class ChartStudy {this.options = options;this.#studyListeners[this.#studID] = async (packet) => {- console.log('§90§30§105 STUDY §0 DATA', packet);+ if (global.TW_DEBUG) console.log('§90§30§105 STUDY §0 DATA', packet);if (packet.type === 'study_completed') {this.#handleEvent('studyCompleted');diff --git a/src/client.js b/src/client.jsindex d75e8aa..8f23ae2 100644--- a/src/client.js+++ b/src/client.js@@ -154,7 +154,7 @@ module.exports = class Client {if (!this.isOpen) return;protocol.parseWSPacket(str).forEach((packet) => {- console.log('§90§30§107 CLIENT §0 PACKET', packet);+ if (global.TW_DEBUG) console.log('§90§30§107 CLIENT §0 PACKET', packet);if (typeof packet === 'number') { // Pingthis.#ws.send(protocol.formatWSPacket(`~h~${packet}`));this.#handleEvent('ping', packet);@@ -209,12 +209,15 @@ module.exports = class Client {/*** @typedef {Object} ClientOptions* @prop {string} [token] User auth token (in 'sessionid' cookie)+ * @prop {boolean} [DEBUG] Enable debug mode*//** Client object* @param {ClientOptions} clientOptions TradingView client options*/constructor(clientOptions = {}) {+ if (clientOptions.DEBUG) global.TW_DEBUG = clientOptions.DEBUG;+this.#ws = new WebSocket('wss://widgetdata.tradingview.com/socket.io/websocket', {origin: 'https://s.tradingview.com',});@@ -222,6 +225,8 @@ module.exports = class Client {if (clientOptions.token) {misc.getUser(clientOptions.token).then((user) => {this.send('set_auth_token', [user.authToken]);+ }).catch((err) => {+ this.#handleError('Credentials error:', err.message);});} else this.send('set_auth_token', ['unauthorized_user_token']);diff --git a/src/quote/market.js b/src/quote/market.jsindex eb1d552..70b3460 100644--- a/src/quote/market.js+++ b/src/quote/market.js@@ -52,7 +52,7 @@ module.exports = (quoteSession) => class QuoteMarket {this.#symbolListenerID = this.#symbolListeners[symbol].length;this.#symbolListeners[symbol][this.#symbolListenerID] = (packet) => {- console.log('§90§30§105 MARKET §0 DATA', packet);+ if (global.TW_DEBUG) console.log('§90§30§105 MARKET §0 DATA', packet);if (packet.type === 'qsd' && packet.data[1].s === 'ok') {this.#lastData = {diff --git a/src/quote/session.js b/src/quote/session.jsindex 1cc647e..45aaa94 100644--- a/src/quote/session.js+++ b/src/quote/session.js@@ -76,7 +76,7 @@ module.exports = (client) => class QuoteSession {this.#client.sessions[this.#sessionID] = {type: 'quote',onData: (packet) => {- console.log('§90§30§102 QUOTE SESSION §0 DATA', packet);+ if (global.TW_DEBUG) console.log('§90§30§102 QUOTE SESSION §0 DATA', packet);if (packet.type === 'quote_completed') {const symbol = packet.data[1];diff --git a/src/types.js b/src/types.jsindex cb63c95..96ef48f 100644--- a/src/types.js+++ b/src/types.js@@ -26,7 +26,7 @@** @typedef {'1' | '3' | '5' | '15' | '30'* | '45' | '60' | '120' | '180' | '240'- * | '1D' | '1W' | '1M'} TimeFrame+ * | '1D' | '1W' | '1M' | 'D' | 'W' | 'M'} TimeFrame*/module.exports = {};