Skip to content

πŸ“ˆ Get real-time stocks from TradingView

[2.0.5] Add 'session' prop and end() func

Mathieu Colmondb6208662daf
diff --git a/main.js b/main.js
index 5b843c4..5ac47b4 100644
--- a/main.js
+++ b/main.js
@@ -1,6 +1,6 @@
const WebSocket = require('ws');
const {
- search, getScreener, getTA, getIndicator,
+ search, getScreener, getTA, getIndicator, getUserToken,
} = require('./miscRequests');
let onPacket = () => null;
@@ -166,33 +166,47 @@ module.exports = (autoInit = true) => {
};
return {
- /**
- * @param {'connected' | 'disconnected' | 'logged'
- * | 'subscribed' | 'price' | 'data' | 'error' | 'ping' } ev
- * @param {(...data: object) => null} cb
+ /** Event listener
+ * @param { 'connected' | 'disconnected' | 'logged'
+ * | 'subscribed' | 'price' | 'data' | 'error' | 'ping' } event Event
+ * @param {(...data: object) => null} cb Callback
*/
- on(ev, cb) {
- if (!callbacks[ev]) {
- console.log('Wrong event:', ev);
+ on(event, cb) {
+ if (!callbacks[event]) {
+ console.log('Wrong event:', event);
console.log('Available events:', Object.keys(callbacks));
return;
}
- callbacks[ev].push(cb);
+ callbacks[event].push(cb);
},
+ /**
+ * Close the websocket connection
+ * @param {string} symbol Market symbol (Example: BTCEUR or COINBASE:BTCEUR)
+ */
+ end() { ws.close(); },
+
search,
getScreener,
getTA,
subscribed,
- subscribe(symbol = '') {
+ /**
+ * Unsubscribe to a market
+ * @param {string} symbol Market symbol (Example: BTCEUR or COINBASE:BTCEUR)
+ */
+ subscribe(symbol) {
if (subscribed.includes(symbol)) return;
send('quote_add_symbols', [sessionId, symbol]);
subscribed.push(symbol);
},
- unsubscribe(symbol = '') {
+ /**
+ * Unsubscribe from a market
+ * @param {string} symbol Market symbol (Example: BTCEUR or COINBASE:BTCEUR)
+ */
+ unsubscribe(symbol) {
if (!subscribed.includes(symbol)) return;
send('quote_remove_symbols', [sessionId, symbol]);
subscribed = subscribed.filter((s) => s !== symbol);
@@ -205,6 +219,7 @@ module.exports = (autoInit = true) => {
* @property {(string | number | boolean | null)[]} [settings] Indicator settings value
*
* @typedef {Object} ChartInfos
+ * @property {string} [session] User 'sessionid' cookie
* @property {string} symbol Market symbol (Example: BTCEUR or COINBASE:BTCEUR)
* @property { '1' | '3' | '5' | '15' | '30' | '45'
* | '60' | '120' | '180' | '240'
@@ -282,6 +297,7 @@ module.exports = (autoInit = true) => {
}
};
+ if (chart.session) send('set_auth_token', [await getUserToken(chart.session)]);
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"}`]);
diff --git a/miscRequests.js b/miscRequests.js
index acaeb29..037f48f 100644
--- a/miscRequests.js
+++ b/miscRequests.js
@@ -255,4 +255,31 @@ module.exports = {
});
});
},
+
+ /**
+ * Get a token for an user from a 'sessionid' cookie
+ * @param {string} session User 'sessionid' cookie
+ * @param {string} [location] Auth page location (For france: https://fr.tradingview.com/)
+ * @returns {Promise<string>} Token
+ */
+ async getUserToken(session, location = 'https://www.tradingview.com/') {
+ return new Promise((cb, err) => {
+ https.get(location, {
+ headers: { cookie: `sessionid=${session}` },
+ }, (res) => {
+ let rs = '';
+ res.on('data', (d) => { rs += d; });
+ res.on('end', async () => {
+ if (res.headers.location && location !== res.headers.location) {
+ cb(await module.exports.getUserToken(session, res.headers.location));
+ return;
+ }
+ if (rs.includes('auth_token')) cb(/"auth_token":"(.*?)"/g.exec(rs)[1]);
+ else err(new Error('Wrong or expired sessionid'));
+ });
+
+ res.on('error', err);
+ }).end();
+ });
+ },
};
diff --git a/package.json b/package.json
index 04ad09d..55b0992 100644
--- a/package.json
+++ b/package.json
@@ -1,14 +1,15 @@
{
"name": "@mathieuc/tradingview",
- "version": "2.0.3",
- "description": "Tradingview instant stocks API",
+ "version": "2.0.5",
+ "description": "Tradingview instant stocks API, indicator alerts, trading bot, and more !",
"main": "main.js",
"scripts": {
"test-prices": "node ./tests/prices.js",
"test-analysis": "node ./tests/analysis.js",
"test-indicator": "node ./tests/indicator.js",
- "test-alerts": "node ./tests/alerts/alerts.js",
- "start-prices": "npm test"
+ "test-manual-alerts": "node ./tests/alerts/manualAlert.js",
+ "test-strat-alerts": "node ./tests/alerts/strategyAlert.js",
+ "test": "npm run test-prices"
},
"keywords": [
"tradingwiew",
diff --git a/tests/alerts/alerts.js b/tests/alerts/manualAlert.js
similarity index 83%
rename from tests/alerts/alerts.js
rename to tests/alerts/manualAlert.js
index 7e34371..0f8459c 100644
--- a/tests/alerts/alerts.js
+++ b/tests/alerts/manualAlert.js
@@ -38,20 +38,6 @@ market.on('logged', () => {
}, (periods) => {
if (!periods[0].CIPHER_B) return;
- // periods.forEach((p, i) => {
- // if (p.CIPHER_B.WTWave1 > 0 || p.CIPHER_B.WTWave1 < -35) return;
-
- // const pBefore = periods[i + 1];
- // if (!pBefore) return;
-
- // const gapBefore = pBefore.CIPHER_B.VWAP;
- // const gap = p.CIPHER_B.VWAP;
- // if (
- // gapBefore < 0 && gapBefore < gap
- // && pBefore.CIPHER_B.WTWave1 < p.CIPHER_B.WTWave1
- // ) console.log(symbol, 'TRIG', new Date(p.$time * 1000).toLocaleString());
- // });
-
const pBefore = periods[1];
const p = periods[0];
diff --git a/tests/alerts/strategyAlert.js b/tests/alerts/strategyAlert.js
index d3f3c1a..893d9da 100644
--- a/tests/alerts/strategyAlert.js
+++ b/tests/alerts/strategyAlert.js
@@ -30,8 +30,8 @@ const markets = [
symbol: 'USDCAD',
period: '1D',
settings: {
- 1: 89, // HMA 1 Length
- 3: 21, // HMA 2 Length
+ 1: 21, // HMA 1 Length
+ 3: 89, // HMA 2 Length
5: 10, // RSI Length
8: 3, // Stop Loss (%)
9: 2, // Take Profit (%)