Skip to content

πŸ“ˆ Get real-time stocks from TradingView

Add Chart API

Mathieu Colmon54b3bb3ed739
diff --git a/README.md b/README.md
index 3a8a979..4ffcf65 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,5 @@
# Tradingview API
-Get realtime stocks from Tradingview
+Get realtime market from Tradingview
___
## Installation
@@ -8,43 +8,103 @@ ___
npm i @mathieuc/tradingview
```
-## Example (test.js)
+## Examples (./tests/)
```javascript
-const stocksAPI = require('tradingview');
+/*
+ ./tests/prices.js
+ Search for Bitcoin and Ethereum and get real time prices
+*/
+
+const marketAPI = require('tradingview');
(async () => {
- const stocks = stocksAPI();
+ const market = marketAPI();
- stocks.on('logged', async () => {
+ market.on('logged', async () => {
console.log('API LOGGED');
- const searchBTC = (await stocks.search('bitcoin euro', 'crypto'))[0];
+ const searchBTC = (await market.search('bitcoin euro', 'crypto'))[0];
console.log('Found Bitcoin / Euro:', searchBTC);
- stocks.subscribe(searchBTC.id);
+ market.subscribe(searchBTC.id);
});
- stocks.on('price', (data) => {
+ market.on('price', (data) => {
console.log(data.symbol, '=>', data.price);
});
- const searchETH = (await stocks.search('ethereum euro', 'crypto'))[0];
+ const searchETH = (await market.search('ethereum euro', 'crypto'))[0];
console.log('Found Ethereum / Euro:', searchETH);
setTimeout(() => {
console.log('Subscribe to', searchETH.id);
- stocks.subscribe(searchETH.id);
+ market.subscribe(searchETH.id);
}, 10000);
setTimeout(() => {
console.log('Unsubscribe from', searchETH.id);
- stocks.unsubscribe(searchETH.id);
+ market.unsubscribe(searchETH.id);
}, 20000);
})();
```
+```javascript
+/*
+ ./tests/analysis.js
+ Search for Bitcoin and get the Technical Analysis in all timeframes
+*/
+
+const marketAPI = require('tradingview');
+
+const market = marketAPI();
+
+market.on('logged', async () => {
+ const searchBTC = (await market.search('bitcoin euro', 'crypto'))[0];
+ console.log('Found Bitcoin / Euro:', searchBTC);
+
+ const TA = await searchBTC.getTA();
+ console.log('Full technical analysis for Bitcoin:', TA);
+
+ // You can also use this way: await market.getTA('crypto', 'BINANCE:BTCEUR');
+});
+```
+
+```javascript
+/*
+ ./tests/indicator.js
+ Get indicator values
+*/
+
+const marketAPI = require('tradingview');
+
+const market = marketAPI(false); // 'false' for chart-only mode
+
+market.on('logged', () => {
+ market.initChart({
+ symbol: 'COINBASE:BTCEUR',
+ period: '240',
+ range: 50,
+ indicators: [
+ { name: 'ACCU_DISTRIB', id: 'STD;Accumulation_Distribution', version: '25' },
+ { name: 'CIPHER_A', id: 'PUB;vrOJcNRPULteowIsuP6iHn3GIxBJdXwT', version: '1.0' },
+ { name: 'CIPHER_B', id: 'PUB;uA35GeckoTA2EfgI63SD2WCSmca4njxp', version: '15.0' },
+ // Color Changing moving average
+ { name: 'CCMA', id: 'PUB;5nawr3gCESvSHQfOhrLPqQqT4zM23w3X', version: '6.0' },
+ ],
+ }, (periods) => {
+ if (!periods[0].CIPHER_B) return;
+ if (!periods[0].CCMA) return;
+
+ console.log('Last period:', {
+ price: periods[0].$prices.close,
+ moneyFlow: (periods[0].CIPHER_B.RSIMFIArea >= 0) ? 'POSITIVE' : 'NEGATIVE',
+ VWAP: periods[0].CIPHER_B.VWAP,
+ MA: (periods[0].CCMA.Plot <= periods[0].$prices.close) ? 'ABOVE' : 'UNDER',
+ });
+ });
+});
+```
___
## Problems
-
- If you have errors in console or unwanted behavior, just reload the page.
- If the problem persists, please create an issue [here](https://github.com/Mathieu2301/Tradingview-API/issues).
+ If you have errors in console or unwanted behavior,
+ please create an issue [here](https://github.com/Mathieu2301/Tradingview-API/issues).
diff --git a/main.js b/main.js
index 4566f89..5b843c4 100644
--- a/main.js
+++ b/main.js
@@ -1,5 +1,7 @@
const WebSocket = require('ws');
-const { search, getScreener, getTA } = require('./miscRequests');
+const {
+ search, getScreener, getTA, getIndicator,
+} = require('./miscRequests');
let onPacket = () => null;
@@ -9,7 +11,7 @@ function parse(str) {
try {
return JSON.parse(p);
} catch (error) {
- console.log('Cant parse', p);
+ console.warn('Cant parse', p);
return false;
}
}).filter((p) => p);
@@ -43,7 +45,7 @@ function genSession() {
return `qs_${r}`;
}
-module.exports = () => {
+module.exports = (autoInit = true) => {
const callbacks = {
connected: [],
disconnected: [],
@@ -57,17 +59,30 @@ module.exports = () => {
event: [],
};
+ const chartEventNames = [
+ 'du', 'timescale_update',
+ 'series_loading', 'series_completed', 'series_error',
+ 'symbol_resolved', 'symbol_error',
+ 'study_loading', 'study_error',
+ ];
+ const chartCBs = {};
+
function handleEvent(ev, ...data) {
callbacks[ev].forEach((e) => e(...data));
callbacks.event.forEach((e) => e(ev, ...data));
}
+ function handleError(...msgs) {
+ if (callbacks.error.length === 0) console.error(...msgs);
+ else handleEvent('error', ...msgs);
+ }
+
const ws = new WebSocket('wss://widgetdata.tradingview.com/socket.io/websocket', {
origin: 'https://s.tradingview.com',
});
let logged = false;
- /** SessionID of the websocket connection */
+ /** ID of the quote session */
let sessionId = '';
/** List of subscribed symbols */
@@ -123,19 +138,26 @@ module.exports = () => {
return;
}
+ if (chartEventNames.includes(packet.type) && chartCBs[packet.session]) {
+ chartCBs[packet.session](packet);
+ return;
+ }
+
if (!logged && packet.type === 'info') {
- send('set_auth_token', ['unauthorized_user_token']);
- send('quote_create_session', [sessionId]);
- send('quote_set_fields', [sessionId, 'lp']);
+ if (autoInit) {
+ send('set_auth_token', ['unauthorized_user_token']);
+ send('quote_create_session', [sessionId]);
+ send('quote_set_fields', [sessionId, 'lp']);
- subscribed.forEach((symbol) => send('quote_add_symbols', [sessionId, symbol]));
+ subscribed.forEach((symbol) => send('quote_add_symbols', [sessionId, symbol]));
+ }
handleEvent('logged', packet);
return;
}
if (packet.type === 'error') {
- handleEvent('error', { message: 'API error, please make sure you have the latest API version', syntax: packet.syntax });
+ handleError(`Market API critical error: ${packet.syntax}`);
ws.close();
return;
}
@@ -176,6 +198,123 @@ module.exports = () => {
subscribed = subscribed.filter((s) => s !== symbol);
},
+ /**
+ * @typedef {Object} IndicatorInfos Indicator infos
+ * @property {string} id ID of the indicator (Like: XXX;XXXXXXXXXXXXXXXXXXXXX)
+ * @property {string} version Wanted version of the indicator
+ * @property {(string | number | boolean | null)[]} [settings] Indicator settings value
+ *
+ * @typedef {Object} ChartInfos
+ * @property {string} symbol Market symbol (Example: BTCEUR or COINBASE:BTCEUR)
+ * @property { '1' | '3' | '5' | '15' | '30' | '45'
+ * | '60' | '120' | '180' | '240'
+ * | '1D' | '1W' | '1M'
+ * } [period] Period
+ * @property {number} [range] Number of loaded periods
+ * @property {string} [timezone] Timezone in 'Europe/Paris' format
+ * @property {IndicatorInfos[]} [indicators] List of indicators
+ */
+
+ /**
+ * @typedef {Object} Period List of prices / indicator values
+ * @property {number} $time
+ * @property {{
+ * time: number, open: number, close: number,
+ * max: number, min: number, change: number,
+ * }} $prices
+ */
+
+ /**
+ * Init a chart instance
+ * @param {ChartInfos} chart
+ * @param {{(prices: Period[]): null}} onUpdate List of periods starting from the lastest
+ */
+ async initChart(chart, onUpdate) {
+ const chartSession = genSession();
+ const periods = [];
+ const indicators = await Promise.all(
+ (chart.indicators || []).map((i) => getIndicator(i.id, i.version, i.settings)),
+ );
+
+ function updatePeriods(packet) {
+ const newData = packet.data;
+
+ Object.keys(newData).forEach((type) => {
+ (newData[type].s || newData[type].st || []).forEach((p) => {
+ if (!periods[p.i]) periods[p.i] = {};
+
+ if (newData[type].s) {
+ [periods[p.i].$time] = p.v;
+
+ periods[p.i][type] = {
+ open: p.v[1],
+ close: p.v[4],
+ max: p.v[2],
+ min: p.v[3],
+ change: Math.round(p.v[5] * 100) / 100,
+ };
+ }
+
+ if (newData[type].st) {
+ const period = {};
+ const indicator = indicators[parseInt(type, 10)];
+
+ p.v.forEach((val, i) => {
+ if (i === 0) return;
+ if (indicator.plots[`plot_${i - 1}`]) period[indicator.plots[`plot_${i - 1}`]] = val;
+ else period[`_plot_${i - 1}`] = val;
+ });
+ periods[p.i][chart.indicators[parseInt(type, 10)].name || `st${type}`] = period;
+ }
+ });
+ });
+ }
+
+ chartCBs[chartSession] = (packet) => {
+ if (['timescale_update', 'du'].includes(packet.type)) {
+ updatePeriods(packet);
+ onUpdate([...periods].reverse());
+ return;
+ }
+
+ if (packet.type.endsWith('_error')) {
+ handleError(`Error on '${chart.symbol}' (${chartSession}) chart: "${packet.type}"`);
+ }
+ };
+
+ send('chart_create_session', [chartSession, '']);
+ if (chart.timezone) send('switch_timezone', [chartSession, chart.timezone]);
+ send('resolve_symbol', [chartSession, 'sds_sym_1', `={"symbol":"${chart.symbol || 'BTCEUR'}","adjustment":"splits"}`]);
+ send('create_series', [chartSession, '$prices', 's1', 'sds_sym_1', (chart.period || '240'), (chart.range || 100), '']);
+
+ indicators.forEach(async (indicator, i) => {
+ const pineInfos = {
+ pineId: indicator.pineId,
+ pineVersion: indicator.pineVersion,
+ text: indicator.script,
+ };
+
+ Object.keys(indicator.inputs).forEach((inputID, inp) => {
+ const input = indicator.inputs[inputID];
+ if (input.type === 'bool' && typeof input.value !== 'boolean') handleError(`Input '${input.name}' (${inp}) must be a boolean !`);
+ if (input.type === 'integer' && typeof input.value !== 'number') handleError(`Input '${input.name}' (${inp}) must be a number !`);
+ if (input.type === 'float' && typeof input.value !== 'number') handleError(`Input '${input.name}' (${inp}) must be a number !`);
+ if (input.type === 'text' && typeof input.value !== 'string') handleError(`Input '${input.name}' (${inp}) must be a string !`);
+ if (input.options && !input.options.includes(input.value)) {
+ handleError(`Input '${input.name}' (${inp}) must be one of these values:`, input.options);
+ }
+
+ pineInfos[inputID] = {
+ v: input.value,
+ f: input.isFake,
+ t: input.type,
+ };
+ });
+
+ send('create_study', [chartSession, `${i}`, 'st1', '$prices', 'Script@tv-scripting-101!', pineInfos]);
+ });
+ },
+
send,
sessionId,
};
diff --git a/miscRequests.js b/miscRequests.js
index 04fa741..acaeb29 100644
--- a/miscRequests.js
+++ b/miscRequests.js
@@ -16,7 +16,7 @@ function fetchScanData(tickers = [], type = '', columns = []) {
res.on('data', (c) => { data += c; });
res.on('end', () => {
if (!data.startsWith('{')) {
- err(new Error('Wrong screener'));
+ err(new Error('Wrong screener or symbol'));
return;
}
try {
@@ -33,17 +33,19 @@ function fetchScanData(tickers = [], type = '', columns = []) {
}
/**
- * @typedef {'STRONG_SELL' | 'SELL' | 'NEUTRAL' | 'BUY' | 'STRONG_BUY'} advice
+ * @typedef {number} advice
+ *
+ * @typedef {{ Other: advice, All: advice, MA: advice }} Period
*
* @typedef {{
- * '1': { Other: advice, All: advice, MA: advice },
- * '5': { Other: advice, All: advice, MA: advice },
- * '15': { Other: advice, All: advice, MA: advice },
- * '60': { Other: advice, All: advice, MA: advice },
- * '240': { Other: advice, All: advice, MA: advice },
- * '1D': { Other: advice, All: advice, MA: advice },
- * '1W': { Other: advice, All: advice, MA: advice },
- * '1M': { Other: advice, All: advice, MA: advice },
+ * '1': Period,
+ * '5': Period,
+ * '15': Period,
+ * '60': Period,
+ * '240': Period,
+ * '1D': Period,
+ * '1W': Period,
+ * '1M': Period,
* }} Periods
*
* @typedef {string | 'forex' | 'crypto'
@@ -51,6 +53,7 @@ function fetchScanData(tickers = [], type = '', columns = []) {
* | 'germany' | 'india' | 'israel' | 'italy'
* | 'luxembourg' | 'poland' | 'sweden' | 'turkey'
* | 'uk' | 'vietnam'} screener
+ * You can use `getScreener(exchange)` function for non-forex and non-crypto markets.
*/
module.exports = {
@@ -79,17 +82,17 @@ module.exports = {
/** Get technical analysis
* @param {screener} screener
- * @param {string} symbol You can use `getScreener(exchange)` function
+ * @param {string} id Full market id (Example: COINBASE:BTCEUR)
* @returns {Promise<Periods>} results
*/
- async getTA(screener, symbol) {
+ async getTA(screener, id) {
const advice = {};
const cols = ['1', '5', '15', '60', '240', '1D', '1W', '1M']
.map((t) => indicators.map((i) => (t !== '1D' ? `${i}|${t}` : i)))
.flat();
- const rs = await fetchScanData([symbol], screener, cols);
+ const rs = await fetchScanData([id], screener, cols);
if (!rs.data || !rs.data[0]) return false;
rs.data[0].d.forEach((val, i) => {
@@ -103,14 +106,15 @@ module.exports = {
},
/**
- * @typedef {{
- * id: string,
- * exchange: string,
- * fullExchange: string,
- * symbol: string,
- * description: string,
- * type: string,
- * }} SearchResult
+ * @typedef {Object} SearchResult
+ * @property {string} id
+ * @property {string} exchange
+ * @property {string} fullExchange
+ * @property {string} screener
+ * @property {string} symbol
+ * @property {string} description
+ * @property {string} type
+ * @property {() => Promise<Periods>} getTA
*/
/**
@@ -134,15 +138,119 @@ module.exports = {
err(new Error('Can\'t parse server response'));
return;
}
- cb(rs.map((s) => ({
- id: `${s.exchange.split(' ')[0]}:${s.symbol}`,
- exchange: s.exchange.split(' ')[0],
- fullExchange: s.exchange,
- symbol: s.symbol,
- description: s.description,
- type: s.type,
- })));
+
+ cb(rs.map((s) => {
+ const exchange = s.exchange.split(' ')[0];
+ const id = `${exchange}:${s.symbol}`;
+
+ const screener = (['forex', 'crypto'].includes(s.type)
+ ? s.type
+ : this.getScreener(exchange)
+ );
+
+ return {
+ id,
+ exchange,
+ fullExchange: s.exchange,
+ screener,
+ symbol: s.symbol,
+ description: s.description,
+ type: s.type,
+ getTA: () => this.getTA(screener, id),
+ };
+ }));
+ });
+
+ res.on('error', err);
+ });
+ });
+ },
+
+ /**
+ * @typedef {Object} indicatorInput
+ * @property {string} name
+ * @property {string} inline Inline name
+ * @property { 'text' | 'source' | 'integer' | 'float' | 'resolution' | 'bool' } type
+ * @property {string | number | boolean} value
+ * @property {string | number | boolean} defVal
+ * @property {boolean} hidden
+ * @property {boolean} isFake
+ * @property {string[]} [options]
+ */
+
+ /**
+ * @typedef {Object} Indicator
+ * @property {string} pineId Indicator ID
+ * @property {string} pineVersion Indicator version
+ * @property {string} description Indicator description
+ * @property {string} shortDescription Indicator short description
+ * @property {Object<string, indicatorInput>} inputs Indicator inputs
+ * @property {Object<string, string>} plots Indicator plots
+ * @property {string} script Indicator script
+ */
+
+ /**
+ * Get an indicator
+ * @param {string} id Indicator ID (Like: PUB;XXXXXXXXXXXXXXXXXXXXX)
+ * @param {string} version Wanted version of the indicator
+ * @returns {Promise<Indicator>} Indicator
+ */
+ async getIndicator(id, version, settings = []) {
+ return new Promise((cb, err) => {
+ https.get(`https://pine-facade.tradingview.com/pine-facade/translate/${id}/${version}`, (res) => {
+ let rs = '';
+ res.on('data', (d) => { rs += d; });
+ res.on('end', () => {
+ try {
+ rs = JSON.parse(rs);
+ } catch (e) {
+ err(new Error('Inexistent or unsupported indicator'));
+ return;
+ }
+
+ if (!rs.success || !rs.result.metaInfo || !rs.result.metaInfo.inputs) {
+ err(new Error('Inexistent or unsupported indicator'));
+ return;
+ }
+
+ const inputs = {};
+
+ rs.result.metaInfo.inputs.forEach((input) => {
+ if (['text', 'pineId', 'pineVersion'].includes(input.id)) return;
+ const inline = input.inline || input.name.replace(/ /g, '_').replace(/[^a-zA-Z0-9]/g, '');
+
+ const i = parseInt(input.id.replace(/[^0-9]/g, ''), 10);
+
+ inputs[input.id] = {
+ name: input.name,
+ type: input.type,
+ value: settings[i] ?? input.defval,
+ defVal: input.defval,
+ hidden: !!input.isHidden,
+ isFake: !!input.isFake,
+ inline,
+ };
+
+ if (input.options) inputs[input.id].options = input.options;
+ });
+
+ const plots = {};
+
+ Object.keys(rs.result.metaInfo.styles).forEach((plotId) => {
+ plots[plotId] = rs.result.metaInfo.styles[plotId].title.replace(/ /g, '_').replace(/[^a-zA-Z0-9]/g, '');
+ });
+
+ cb({
+ pineId: id,
+ pineVersion: version,
+ description: rs.result.metaInfo.description,
+ shortDescription: rs.result.metaInfo.shortDescription,
+ inputs,
+ plots,
+ script: rs.result.ilTemplate,
+ });
});
+
res.on('error', err);
});
});
diff --git a/package.json b/package.json
index df907ea..65a58f8 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,9 @@
"description": "Tradingview instant stocks API",
"main": "main.js",
"scripts": {
- "test": "node test",
+ "test-prices": "node ./tests/prices.js",
+ "test-analysis": "node ./tests/analysis.js",
+ "test-indicator": "node ./tests/indicator.js",
"start": "npm test"
},
"keywords": [
diff --git a/tests/analysis.js b/tests/analysis.js
new file mode 100644
index 0000000..79a41fd
--- /dev/null
+++ b/tests/analysis.js
@@ -0,0 +1,13 @@
+const marketAPI = require('../main');
+
+const market = marketAPI();
+
+market.on('logged', async () => {
+ const searchBTC = (await market.search('bitcoin euro', 'crypto'))[0];
+ console.log('Found Bitcoin / Euro:', searchBTC);
+
+ const TA = await searchBTC.getTA();
+ console.log('Full technical analysis for Bitcoin:', TA);
+
+ // You can also use this way: await market.getTA('crypto', 'BINANCE:BTCEUR');
+});
diff --git a/tests/indicator.js b/tests/indicator.js
new file mode 100644
index 0000000..9b6ac1d
--- /dev/null
+++ b/tests/indicator.js
@@ -0,0 +1,42 @@
+const marketAPI = require('../main');
+
+const market = marketAPI(false);
+
+market.on('logged', () => {
+ market.initChart({
+ symbol: 'COINBASE:BTCEUR',
+ period: '240',
+ range: 50,
+ indicators: [
+ { name: 'ACCU_DISTRIB', id: 'STD;Accumulation_Distribution', version: '25' },
+ { name: 'CIPHER_A', id: 'PUB;vrOJcNRPULteowIsuP6iHn3GIxBJdXwT', version: '1.0' },
+ {
+ name: 'CIPHER_B',
+ id: 'PUB;uA35GeckoTA2EfgI63SD2WCSmca4njxp',
+ settings: [ // Activate Stoch divergences
+ true, true, true, true, true, true, 9, 12,
+ 'hlc3', 3, 53, 60, 100, -53, -60, -75, true,
+ true, true, 45, -65, true, 15, -40, true, 60,
+ 150, 2.5, false, 'close', 14, 30, 60, false,
+ false, 60, 30, true, true, false, 'close', 14,
+ 14, 3, 3, true, true, false, 'close', 10, 23,
+ 50, 0.5, false, false, '720', 0, 0, 0, 0, 0, 0,
+ false, '60', '240', 0, 0, false, '240', false,
+ ],
+ version: '15.0',
+ },
+ // Color Changing Moving Average
+ { name: 'CCMA', id: 'PUB;5nawr3gCESvSHQfOhrLPqQqT4zM23w3X', version: '6.0' },
+ ],
+ }, (periods) => {
+ if (!periods[0].CIPHER_B) return;
+ if (!periods[0].CCMA) return;
+
+ console.log('Last period:', {
+ price: periods[0].$prices.close,
+ moneyFlow: (periods[0].CIPHER_B.RSIMFIArea >= 0) ? 'POSITIVE' : 'NEGATIVE',
+ VWAP: periods[0].CIPHER_B.VWAP,
+ MA: (periods[0].CCMA.Plot <= periods[0].$prices.close) ? 'ABOVE' : 'UNDER',
+ });
+ });
+});
diff --git a/test.js b/tests/prices.js
similarity index 52%
rename from test.js
rename to tests/prices.js
index cf6b428..944fd73 100644
--- a/test.js
+++ b/tests/prices.js
@@ -1,33 +1,33 @@
-const stocksAPI = require('./main');
+const marketAPI = require('../main');
(async () => {
- const stocks = stocksAPI();
+ const market = marketAPI();
- stocks.on('logged', async () => {
+ market.on('logged', async () => {
console.log('API LOGGED');
- const searchBTC = (await stocks.search('bitcoin euro', 'crypto'))[0];
+ const searchBTC = (await market.search('bitcoin euro', 'crypto'))[0];
console.log('Found Bitcoin / Euro:', searchBTC);
- stocks.subscribe(searchBTC.id);
+ market.subscribe(searchBTC.id);
- const btcTA = (await stocks.getTA(searchBTC.type, searchBTC.id));
+ const btcTA = (await market.getTA(searchBTC.type, searchBTC.id));
console.log('Technical Analysis for Bitcoin / Euro:', btcTA);
});
- stocks.on('price', (data) => {
+ market.on('price', (data) => {
console.log(data.symbol, '=>', data.price);
});
- const searchETH = (await stocks.search('ethereum euro', 'crypto'))[0];
+ const searchETH = (await market.search('ethereum euro', 'crypto'))[0];
console.log('Found Ethereum / Euro:', searchETH);
setTimeout(() => {
console.log('Subscribe to', searchETH.id);
- stocks.subscribe(searchETH.id);
+ market.subscribe(searchETH.id);
}, 10000);
setTimeout(() => {
console.log('Unsubscribe from', searchETH.id);
- stocks.unsubscribe(searchETH.id);
+ market.unsubscribe(searchETH.id);
}, 20000);
})();