Skip to content

πŸ“ˆ Get real-time stocks from TradingView

Init commit

Mathieu Colmon1d255bf0d7da
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..dfe0770
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+# Auto detect text files and perform LF normalization
+* text=auto
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..d5f19d8
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+node_modules
+package-lock.json
diff --git a/.npmignore b/.npmignore
new file mode 100644
index 0000000..d5f19d8
--- /dev/null
+++ b/.npmignore
@@ -0,0 +1,2 @@
+node_modules
+package-lock.json
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..3619f05
--- /dev/null
+++ b/README.md
@@ -0,0 +1,50 @@
+# Tradingview API
+Get realtime stocks from Tradingview
+
+___
+## Installation
+
+```
+npm i tradingview
+```
+
+## Example (test.js)
+
+```javascript
+const stocksAPI = require('tradingview');
+
+(async () => {
+ const stocks = stocksAPI();
+
+ stocks.on('logged', async () => {
+ console.log('API LOGGED');
+
+ const searchBTC = (await stocks.search('bitcoin euro', 'crypto'))[0];
+ console.log('Found Bitcoin / Euro:', searchBTC);
+ stocks.subscribe(searchBTC.id);
+ });
+
+ stocks.on('price', (data) => {
+ console.log(data.symbol, '=>', data.price);
+ });
+
+ const searchETH = (await stocks.search('ethereum euro', 'crypto'))[0];
+ console.log('Found Ethereum / Euro:', searchETH);
+
+ setTimeout(() => {
+ console.log('Subscribe to', searchETH.id);
+ stocks.subscribe(searchETH.id);
+ }, 10000);
+
+ setTimeout(() => {
+ console.log('Unsubscribe from', searchETH.id);
+ stocks.unsubscribe(searchETH.id);
+ }, 20000);
+})();
+```
+
+___
+## 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).
diff --git a/main.js b/main.js
new file mode 100644
index 0000000..13488fd
--- /dev/null
+++ b/main.js
@@ -0,0 +1,173 @@
+const WebSocket = require('ws');
+const https = require('https');
+
+function parse(str) {
+ const data = JSON.parse(str.split('~').pop());
+
+ if (data.m === 'protocol_error') return {
+ type: 'error',
+ syntax: data.p[0],
+ }
+
+ if (data.m && data.p) return {
+ type: data.m,
+ session: data.p[0],
+ data: data.p[1],
+ }
+
+ if (typeof data === 'number') return { type: 'ping', ping: data }
+
+ return { type: 'info', ...data }
+}
+
+function genSession() {
+ let r = '';
+ const c = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
+ for (let i = 0; i < 12; i++) r += c.charAt(Math.floor(Math.random() * c.length));
+ return `qs_${r}`;
+}
+
+module.exports = () => {
+ const callbacks = {
+ connected: [],
+ disconnected: [],
+ logged: [],
+ subscribed: [],
+ ping: [],
+ price: [],
+ data: [],
+
+ error: [],
+ event: [],
+ };
+
+ let ws = new WebSocket('wss://widgetdata.tradingview.com/socket.io/websocket?from=embed-widget%2Fmini-symbol-overview%2F&date=2021_03_04-12_35', {
+ origin: 'https://s.tradingview.com',
+ });
+
+ function send(m = '', p = []) {
+ if (!session) return;
+
+ const msg = JSON.stringify({ m, p });
+ ws.send(`~m~${msg.length}~m~${msg}`);
+ }
+
+ let logged = false;
+ let session = '';
+
+ ws.on('open', () => {
+ session = genSession();
+ handleEvent('connected');
+ });
+
+ ws.on('close', () => {
+ logged = false;
+ session = '';
+ handleEvent('disconnected');
+ });
+
+ ws.on('message', (str) => {
+ const data = parse(str);
+
+ if (data.type === 'ping') {
+ const pingStr = `~h~${data.ping}`;
+ ws.send(`~m~${pingStr.length}~m~${pingStr}`);
+ handleEvent('ping', data.ping);
+ return;
+ }
+
+ if (data.type === 'quote_completed' && data.data) {
+ handleEvent('subscribed', data.data);
+ return;
+ }
+
+ if (data.type === 'qsd' && data.data.n && data.data.v.lp) {
+ handleEvent('price', {
+ symbol: data.data.n,
+ price: data.data.v.lp,
+ });
+
+ return;
+ }
+
+ if (!logged && data.type === 'info') {
+ send('set_auth_token', ['unauthorized_user_token']);
+ send('quote_create_session', [session]);
+ send('quote_set_fields', [session, 'lp']);
+
+ handleEvent('logged', data);
+ return;
+ }
+
+ if (data.type === 'error') {
+ handleEvent('error', { message: 'API error, please make sure you have the latest API version', syntax: data.syntax });
+ return;
+ }
+
+ handleEvent('data', data);
+ });
+
+ function handleEvent(ev, ...data) {
+ callbacks[ev].forEach((e) => e(...data));
+ callbacks.event.forEach((e) => e(ev, ...data));
+ }
+
+ return {
+ on(ev, cb) {
+ if (!callbacks[ev]) {
+ console.log('Wrong event:', ev);
+ console.log('Available events:', Object.keys(callbacks));
+ return;
+ }
+
+ callbacks[ev].push(cb);
+ },
+
+ async search(search, filter = '') {
+ return new Promise((cb, err) => {
+ https.get({
+ host: 'symbol-search.tradingview.com',
+ path: `/symbol_search/?text=${search.replace(/ /g, '%20')}&type=${filter}`,
+ origin: 'https://www.tradingview.com',
+ }, (res) => {
+ let rs = '';
+ res.on('data', (d) => rs += d);
+ res.on('end', () => {
+ try {
+ rs = JSON.parse(rs);
+ } catch (e) {
+ err(new Error('Can\'t parse server response'));
+ return;
+ }
+ cb(rs.map((s) => ({
+ id: `${s.exchange}:${s.symbol}`,
+ symbol: s.symbol,
+ description: s.description,
+ type: s.type,
+ })));
+ });
+ res.on('error', (e) => {
+ err(e);
+ return;
+ });
+ })
+ });
+ },
+
+ subscribed: [],
+
+ subscribe(symbol = '') {
+ if (this.subscribed.includes(symbol)) return;
+ send('quote_add_symbols', [session, symbol]);
+ this.subscribed.push(symbol);
+ },
+
+ unsubscribe(symbol = '') {
+ if (!this.subscribed.includes(symbol)) return;
+ send('quote_remove_symbols', [session, symbol]);
+ this.subscribed = this.subscribed.filter((s) => s !== symbol);
+ },
+
+ send,
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..afaa464
--- /dev/null
+++ b/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "tradingview",
+ "version": "1.0.0",
+ "description": "Tradingview instant stocks API",
+ "main": "main.js",
+ "scripts": {
+ "test": "node test",
+ "start": "npm test"
+ },
+ "keywords": [
+ "tradingwiew",
+ "api"
+ ],
+ "author": "Mathieu Colmon",
+ "license": "ISC",
+ "dependencies": {
+ "ws": "^7.4.3"
+ }
+}
diff --git a/test.js b/test.js
new file mode 100644
index 0000000..bde02a2
--- /dev/null
+++ b/test.js
@@ -0,0 +1,30 @@
+const stocksAPI = require('./main');
+
+(async () => {
+ const stocks = stocksAPI();
+
+ stocks.on('logged', async () => {
+ console.log('API LOGGED');
+
+ const searchBTC = (await stocks.search('bitcoin euro', 'crypto'))[0];
+ console.log('Found Bitcoin / Euro:', searchBTC);
+ stocks.subscribe(searchBTC.id);
+ });
+
+ stocks.on('price', (data) => {
+ console.log(data.symbol, '=>', data.price);
+ });
+
+ const searchETH = (await stocks.search('ethereum euro', 'crypto'))[0];
+ console.log('Found Ethereum / Euro:', searchETH);
+
+ setTimeout(() => {
+ console.log('Subscribe to', searchETH.id);
+ stocks.subscribe(searchETH.id);
+ }, 10000);
+
+ setTimeout(() => {
+ console.log('Unsubscribe from', searchETH.id);
+ stocks.unsubscribe(searchETH.id);
+ }, 20000);
+})();