📈 Get real-time stocks from TradingView
TypeScript backtestingbacktesting-trading-strategiesbitcoinchartscryptocryptocurrencyethereumrealtime-stocksstocksstocks-apistocks-pricestradingtradingviewtradingview-apitradingview-indicatortradingview-replaytradingview-scraper
Better tests + Use Axios + Fixes
Mathieu Colmon401936ff371f
diff --git a/.gitignore b/.gitignoreindex 1945131..713d500 100644--- a/.gitignore+++ b/.gitignore@@ -1,3 +1,2 @@node_modules/-package-lock.json.envdiff --git a/.npmignore b/.npmignoreindex 89a3bb6..74127ac 100644--- a/.npmignore+++ b/.npmignore@@ -1,4 +1,4 @@node_modules/.github/-package-lock.json+tests/.envdiff --git a/examples/AllPrivateIndicators.js b/examples/AllPrivateIndicators.jsindex 811b09d..c085bec 100644--- a/examples/AllPrivateIndicators.js+++ b/examples/AllPrivateIndicators.js@@ -1,14 +1,15 @@const TradingView = require('../main');-/*- This example creates a chart with- all user's private indicators-*/+/**+ * This example creates a chart with all user's private indicators+ */if (!process.argv[2]) throw Error('Please specify your \'sessionid\' cookie');+if (!process.argv[3]) throw Error('Please specify your \'signature\' cookie');const client = new TradingView.Client({token: process.argv[2],+ signature: process.argv[3],});const chart = new client.Session.Chart();diff --git a/examples/BuiltInIndicator.js b/examples/BuiltInIndicator.jsindex ede156b..bc63204 100644--- a/examples/BuiltInIndicator.js+++ b/examples/BuiltInIndicator.js@@ -1,9 +1,8 @@const TradingView = require('../main');-/*- This example tests built-in indicators- like volume-based indicators-*/+/**+ * This example tests built-in indicators like volume-based indicators+ */const volumeProfile = new TradingView.BuiltInIndicator('VbPFixed@tv-basicstudies-139!');diff --git a/examples/CustomChartType.js b/examples/CustomChartType.jsindex ab88355..2fb9047 100644--- a/examples/CustomChartType.js+++ b/examples/CustomChartType.js@@ -1,11 +1,9 @@const TradingView = require('../main');-/*- This example creates charts of custom- types such as 'HeikinAshi', 'Renko',- 'LineBreak', 'Kagi', 'PointAndFigure',- and 'Range' with default settings-*/+/**+ * This example creates charts of custom types such as 'HeikinAshi', 'Renko',+ * 'LineBreak', 'Kagi', 'PointAndFigure', and 'Range' with default settings.+ */const client = new TradingView.Client({/* Token is only required if you want to use intradaydiff --git a/examples/CustomTimeframe.js b/examples/CustomTimeframe.jsindex da91436..73c4f75 100644--- a/examples/CustomTimeframe.js+++ b/examples/CustomTimeframe.js@@ -1,9 +1,8 @@const TradingView = require('../main');-/*- This example tests custom- timeframes like 1 second-*/+/**+ * This example tests custom timeframes like 1 second+ */if (!process.argv[2]) throw Error('Please specify your \'sessionid\' cookie');diff --git a/examples/Errors.js b/examples/Errors.jsindex fed05cb..8ec7263 100644--- a/examples/Errors.js+++ b/examples/Errors.js@@ -1,8 +1,8 @@const TradingView = require('../main');-/*- This example tests many types of errors-*/+/**+ * This example tests many types of errors+ */const client = new TradingView.Client(); // Creates a websocket clientdiff --git a/examples/FakeReplayMode.js b/examples/FakeReplayMode.jsindex 36799a6..441b6d8 100644--- a/examples/FakeReplayMode.js+++ b/examples/FakeReplayMode.js@@ -1,10 +1,9 @@const { Client } = require('../main');-/*- This example tests the fake- replay mode which works in- intraday even with free plan-*/+/**+ * This example tests the fake replay mode which+ * works in intraday even with free plan+ */console.log('----- Testing FakeReplayMode: -----');diff --git a/examples/FromToData.js b/examples/FromToData.jsindex af47728..cacab04 100644--- a/examples/FromToData.js+++ b/examples/FromToData.js@@ -1,10 +1,9 @@const TradingView = require('../main');-/*- This example tests fetching chart- data of a number of candles before- or after a timestamp-*/+/**+ * This example tests fetching chart data of a number+ * of candles before or after a timestamp+ */const client = new TradingView.Client();diff --git a/examples/GetDrawings.js b/examples/GetDrawings.jsindex 7222579..e848b70 100644--- a/examples/GetDrawings.js+++ b/examples/GetDrawings.js@@ -1,9 +1,8 @@const TradingView = require('../main');-/*- This example tests the- getDrawings function-*/+/**+ * This example tests the getDrawings function+ */// First parameter must be the layoutID// (if the layout is private) Second parameter must be the sessionid cookiediff --git a/examples/GraphicIndicator.js b/examples/GraphicIndicator.jsindex 303d64d..d4e926f 100644--- a/examples/GraphicIndicator.js+++ b/examples/GraphicIndicator.js@@ -1,10 +1,9 @@const TradingView = require('../main');-/*- This example tests an indicator that sends- graphic data such as 'lines', 'labels',- 'boxes', 'tables', 'polygons', etc...-*/+/**+ * This example tests an indicator that sends graphic data such+ * as 'lines', 'labels', 'boxes', 'tables', 'polygons', etc...+ */const client = new TradingView.Client();diff --git a/examples/MultipleSyncFetch.js b/examples/MultipleSyncFetch.jsindex 46c56c6..fde4da7 100644--- a/examples/MultipleSyncFetch.js+++ b/examples/MultipleSyncFetch.js@@ -1,9 +1,8 @@const TradingView = require('../main');-/*- This examples synchronously- fetches data from 3 indicators-*/+/**+ * This examples synchronously fetches data from 3 indicators+ */const client = new TradingView.Client();const chart = new client.Session.Chart();diff --git a/examples/PinePermManage.js b/examples/PinePermManage.jsindex 29db2aa..2bf40c5 100644--- a/examples/PinePermManage.js+++ b/examples/PinePermManage.js@@ -1,15 +1,15 @@const { PinePermManager } = require('../main');-/*- This example creates a pine- permission manager and tests- all the available functions-*/+/**+ * This example creates a pine permission manager+ * and tests all the available functions+ */const sessionid = process.argv[2];-const pineid = process.argv[3];+const signature = process.argv[3];+const pineid = process.argv[4];-const manager = new PinePermManager(sessionid, pineid);+const manager = new PinePermManager(sessionid, signature, pineid);(async () => {console.log('Users:', await manager.getUsers());diff --git a/examples/ReplayMode.js b/examples/ReplayMode.jsindex 37a7199..1c28eae 100644--- a/examples/ReplayMode.js+++ b/examples/ReplayMode.js@@ -1,10 +1,9 @@const TradingView = require('../main');-/*- This example tests the real replay- mode by fetching indicator data and- stores it in a 'periods' variable-*/+/**+ * This example tests the real replay mode by fetching+ * indicator data and stores it in a 'periods' variable+ */const config = {symbol: 'BINANCE:BTCEUR',diff --git a/examples/Search.js b/examples/Search.jsindex 4410258..1635177 100644--- a/examples/Search.js+++ b/examples/Search.js@@ -1,10 +1,9 @@const TradingView = require('../main');-/*- This example tests the searching- functions such as 'searchMarket'- and 'searchIndicator'-*/+/**+ * This example tests the searching functions such+ * as 'searchMarket' and 'searchIndicator'+ */TradingView.searchMarket('BINANCE:').then((rs) => {console.log('Found Markets:', rs);diff --git a/examples/SimpleChart.js b/examples/SimpleChart.jsindex 26d15e6..877029d 100644--- a/examples/SimpleChart.js+++ b/examples/SimpleChart.js@@ -1,8 +1,8 @@const TradingView = require('../main');-/*- This example creates a BTCEUR daily chart-*/+/**+ * This example creates a BTCEUR daily chart+ */const client = new TradingView.Client(); // Creates a websocket clientdiff --git a/examples/UserLogin.js b/examples/UserLogin.jsindex e9b2f19..1aeb43a 100644--- a/examples/UserLogin.js+++ b/examples/UserLogin.js@@ -1,9 +1,8 @@const TradingView = require('../main');-/*- This example tests the- user login function-*/+/**+ * This example tests the user login function+ */if (!process.argv[2]) throw Error('Please specify your username/email');if (!process.argv[3]) throw Error('Please specify your password');@@ -11,6 +10,7 @@ if (!process.argv[3]) throw Error('Please specify your password');TradingView.loginUser(process.argv[2], process.argv[3], false).then((user) => {console.log('User:', user);console.log('Sessionid:', user.session);+ console.log('Signature:', user.signature);}).catch((err) => {console.error('Login error:', err.message);});diff --git a/package-lock.json b/package-lock.jsonindex c888cfa..167c2b5 100644--- a/package-lock.json+++ b/package-lock.json@@ -9,12 +9,14 @@"version": "3.4.1","license": "ISC","dependencies": {+ "axios": "^1.5.0","jszip": "^3.7.1","ws": "^7.4.3"},"devDependencies": {"@babel/eslint-parser": "^7.15.7","@mathieuc/console": "^1.0.1",+ "dotenv": "^16.3.1","eslint": "^7.25.0","eslint-config-airbnb-base": "^14.2.1","eslint-plugin-import": "^2.22.1",@@ -1251,6 +1253,21 @@"node": ">=8"}},+ "node_modules/asynckit": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="+ },+ "node_modules/axios": {+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.5.0.tgz",+ "integrity": "sha512-D4DdjDo5CY50Qms0qGQTTw6Q44jl7zRwY7bthds06pUGfChBCTcQs+N743eFWGEd6pRTMd6A+I87aWyFV5wiZQ==",+ "dependencies": {+ "follow-redirects": "^1.15.0",+ "form-data": "^4.0.0",+ "proxy-from-env": "^1.1.0"+ }+ },"node_modules/balanced-match": {"version": "1.0.2","resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",@@ -1414,6 +1431,17 @@"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==","dev": true},+ "node_modules/combined-stream": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",+ "dependencies": {+ "delayed-stream": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/concat-map": {"version": "0.0.1","resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",@@ -1533,6 +1561,14 @@"node": ">= 0.4"}},+ "node_modules/delayed-stream": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",+ "engines": {+ "node": ">=0.4.0"+ }+ },"node_modules/doctrine": {"version": "3.0.0","resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz",@@ -1545,6 +1581,18 @@"node": ">=6.0.0"}},+ "node_modules/dotenv": {+ "version": "16.3.1",+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz",+ "integrity": "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==",+ "dev": true,+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/motdotla/dotenv?sponsor=1"+ }+ },"node_modules/electron-to-chromium": {"version": "1.3.857","resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.857.tgz",@@ -2123,6 +2171,38 @@"integrity": "sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==","dev": true},+ "node_modules/follow-redirects": {+ "version": "1.15.2",+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz",+ "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==",+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/RubenVerborgh"+ }+ ],+ "engines": {+ "node": ">=4.0"+ },+ "peerDependenciesMeta": {+ "debug": {+ "optional": true+ }+ }+ },+ "node_modules/form-data": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",+ "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",+ "dependencies": {+ "asynckit": "^0.4.0",+ "combined-stream": "^1.0.8",+ "mime-types": "^2.1.12"+ },+ "engines": {+ "node": ">= 6"+ }+ },"node_modules/fs.realpath": {"version": "1.0.0","resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",@@ -2772,6 +2852,25 @@"node": ">=8.6"}},+ "node_modules/mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "dependencies": {+ "mime-db": "1.52.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },"node_modules/minimatch": {"version": "3.1.2","resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",@@ -3247,6 +3346,11 @@"node": ">=0.4.0"}},+ "node_modules/proxy-from-env": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",+ "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="+ },"node_modules/punycode": {"version": "2.1.1","resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz",@@ -5027,6 +5131,21 @@"integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==","dev": true},+ "asynckit": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="+ },+ "axios": {+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.5.0.tgz",+ "integrity": "sha512-D4DdjDo5CY50Qms0qGQTTw6Q44jl7zRwY7bthds06pUGfChBCTcQs+N743eFWGEd6pRTMd6A+I87aWyFV5wiZQ==",+ "requires": {+ "follow-redirects": "^1.15.0",+ "form-data": "^4.0.0",+ "proxy-from-env": "^1.1.0"+ }+ },"balanced-match": {"version": "1.0.2","resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",@@ -5149,6 +5268,14 @@"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==","dev": true},+ "combined-stream": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",+ "requires": {+ "delayed-stream": "~1.0.0"+ }+ },"concat-map": {"version": "0.0.1","resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",@@ -5245,6 +5372,11 @@"object-keys": "^1.0.12"}},+ "delayed-stream": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="+ },"doctrine": {"version": "3.0.0","resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz",@@ -5254,6 +5386,12 @@"esutils": "^2.0.2"}},+ "dotenv": {+ "version": "16.3.1",+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz",+ "integrity": "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==",+ "dev": true+ },"electron-to-chromium": {"version": "1.3.857","resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.857.tgz",@@ -5726,6 +5864,21 @@"integrity": "sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==","dev": true},+ "follow-redirects": {+ "version": "1.15.2",+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz",+ "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA=="+ },+ "form-data": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",+ "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",+ "requires": {+ "asynckit": "^0.4.0",+ "combined-stream": "^1.0.8",+ "mime-types": "^2.1.12"+ }+ },"fs.realpath": {"version": "1.0.0","resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",@@ -6203,6 +6356,19 @@"picomatch": "^2.3.1"}},+ "mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="+ },+ "mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "requires": {+ "mime-db": "1.52.0"+ }+ },"minimatch": {"version": "3.1.2","resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",@@ -6556,6 +6722,11 @@"integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==","dev": true},+ "proxy-from-env": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",+ "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="+ },"punycode": {"version": "2.1.1","resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz",diff --git a/package.json b/package.jsonindex 8202645..0c07269 100644--- a/package.json+++ b/package.json@@ -26,12 +26,14 @@"author": "Mathieu Colmon","license": "ISC","dependencies": {+ "axios": "^1.5.0","jszip": "^3.7.1","ws": "^7.4.3"},"devDependencies": {"@babel/eslint-parser": "^7.15.7","@mathieuc/console": "^1.0.1",+ "dotenv": "^16.3.1","eslint": "^7.25.0","eslint-config-airbnb-base": "^14.2.1","eslint-plugin-import": "^2.22.1",diff --git a/src/FormData.js b/src/FormData.jsdeleted file mode 100644index aab3af6..0000000--- a/src/FormData.js+++ /dev/null@@ -1,36 +0,0 @@-/** @class */-class FormData {- #string = '';-- #boundary = '';-- get boundary() {- return this.#boundary;- }-- constructor() {- const random = (Math.random() * 10 ** 20).toString(36);- this.#boundary = `${random}`;- this.#string = `--${this.boundary}`;- }-- /**- * Adds a property to the FormData object- * @param {string} key Property key- * @param {string} value Property value- */- append(key, value) {- this.#string += `\r\nContent-Disposition: form-data; name="${key}"`;- this.#string += `\r\n\r\n${value}`;- this.#string += `\r\n--${this.boundary}`;- }-- /**- * @returns {string}- */- toString() {- return `${this.#string}--`;- }-}--module.exports = FormData;diff --git a/src/classes/PinePermManager.js b/src/classes/PinePermManager.jsindex 02d03c8..f5f55b6 100644--- a/src/classes/PinePermManager.js+++ b/src/classes/PinePermManager.js@@ -1,5 +1,4 @@-const request = require('../request');-const FormData = require('../FormData');+const axios = require('axios');/*** @typedef {Object} AuthorizationUser@@ -18,14 +17,17 @@ class PinePermManager {/*** Creates a PinePermManager instance- * @param {string} sessionId Token from sessionid cookie+ * @param {string} sessionId Token from `sessionid` cookie+ * @param {string} signature Signature cookie* @param {string} pineId Indicator ID (Like: PUB;XXXXXXXXXXXXXXXXXXXXX)*/- constructor(sessionId, pineId) {+ constructor(sessionId, signature, pineId) {if (!sessionId) throw new Error('Please provide a SessionID');+ if (!signature) throw new Error('Please provide a Signature');if (!pineId) throw new Error('Please provide a PineID');- this.pineId = pineId;this.sessionId = sessionId;+ this.signature = signature;+ this.pineId = pineId;}/**@@ -40,20 +42,23 @@ class PinePermManager {* @returns {AuthorizationUser[]}*/async getUsers(limit = 10, order = '-created') {- const { data } = await request({- method: 'POST',- host: 'www.tradingview.com',- path: `/pine_perm/list_users/?limit=${limit}&order_by=${order}`,- headers: {- origin: 'https://www.tradingview.com',- 'Content-Type': 'application/x-www-form-urlencoded',- cookie: `sessionid=${this.sessionId}`,- },- }, false, `pine_id=${this.pineId.replace(/;/g, '%3B')}`);-- if (!data.results) throw new Error('Wrong sessionId or pineId');-- return data.results;+ try {+ const { data } = await axios.post(+ `https://www.tradingview.com/pine_perm/list_users/?limit=${limit}&order_by=${order}`,+ `pine_id=${this.pineId.replace(/;/g, '%3B')}`,+ {+ headers: {+ origin: 'https://www.tradingview.com',+ 'Content-Type': 'application/x-www-form-urlencoded',+ cookie: `sessionid=${this.sessionId};sessionid_sign=${this.signature};`,+ },+ },+ );++ return data.results;+ } catch (e) {+ throw new Error(e.response.data.detail || 'Wrong credentials or pineId');+ }}/**@@ -63,26 +68,31 @@ class PinePermManager {* @returns {'ok' | 'exists' | null}*/async addUser(username, expiration = null) {- const formData = new FormData();- formData.append('pine_id', this.pineId);- formData.append('username_recip', username);- if (expiration && expiration instanceof Date) {- formData.append('expiration', expiration.toString());+ try {+ const { data } = await axios.post(+ 'https://www.tradingview.com/pine_perm/add/',+ `pine_id=${+ this.pineId.replace(/;/g, '%3B')+ }&username_recip=${+ username+ }${+ expiration && expiration instanceof Date+ ? `&expiration=${expiration.toISOString()}`+ : ''+ }`,+ {+ headers: {+ origin: 'https://www.tradingview.com',+ 'Content-Type': 'application/x-www-form-urlencoded',+ cookie: `sessionid=${this.sessionId};sessionid_sign=${this.signature};`,+ },+ },+ );++ return data.status;+ } catch (e) {+ throw new Error(e.response.data.detail || 'Wrong credentials or pineId');}-- const { data } = await request({- method: 'POST',- host: 'www.tradingview.com',- path: '/pine_perm/add/',- headers: {- origin: 'https://www.tradingview.com',- 'Content-Type': `multipart/form-data; boundary=${formData.boundary}`,- cookie: `sessionid=${this.sessionId}`,- },- }, false, formData.toString());-- if (!data.status) throw new Error('Wrong sessionId or pineId');- return data.status;}/**@@ -92,26 +102,31 @@ class PinePermManager {* @returns {'ok' | null}*/async modifyExpiration(username, expiration = null) {- const formData = new FormData();- formData.append('pine_id', this.pineId);- formData.append('username_recip', username);- if (expiration && expiration instanceof Date) {- formData.append('expiration', expiration.toISOString());+ try {+ const { data } = await axios.post(+ 'https://www.tradingview.com/pine_perm/modify_user_expiration/',+ `pine_id=${+ this.pineId.replace(/;/g, '%3B')+ }&username_recip=${+ username+ }${+ expiration && expiration instanceof Date+ ? `&expiration=${expiration.toISOString()}`+ : ''+ }`,+ {+ headers: {+ origin: 'https://www.tradingview.com',+ 'Content-Type': 'application/x-www-form-urlencoded',+ cookie: `sessionid=${this.sessionId};sessionid_sign=${this.signature};`,+ },+ },+ );++ return data.status;+ } catch (e) {+ throw new Error(e.response.data.detail || 'Wrong credentials or pineId');}-- const { data } = await request({- method: 'POST',- host: 'www.tradingview.com',- path: '/pine_perm/modify_user_expiration/',- headers: {- origin: 'https://www.tradingview.com',- 'Content-Type': `multipart/form-data; boundary=${formData.boundary}`,- cookie: `sessionid=${this.sessionId}`,- },- }, false, formData.toString());-- if (!data.status) throw new Error('Wrong sessionId or pineId');- return data.status;}/**@@ -120,23 +135,23 @@ class PinePermManager {* @returns {'ok' | null}*/async removeUser(username) {- const formData = new FormData();- formData.append('pine_id', this.pineId);- formData.append('username_recip', username);-- const { data } = await request({- method: 'POST',- host: 'www.tradingview.com',- path: '/pine_perm/remove/',- headers: {- origin: 'https://www.tradingview.com',- 'Content-Type': `multipart/form-data; boundary=${formData.boundary}`,- cookie: `sessionid=${this.sessionId}`,- },- }, false, formData.toString());-- if (!data.status) throw new Error('Wrong sessionId or pineId');- return data.status;+ try {+ const { data } = await axios.post(+ 'https://www.tradingview.com/pine_perm/remove/',+ `pine_id=${this.pineId.replace(/;/g, '%3B')}&username_recip=${username}`,+ {+ headers: {+ origin: 'https://www.tradingview.com',+ 'Content-Type': 'application/x-www-form-urlencoded',+ cookie: `sessionid=${this.sessionId};sessionid_sign=${this.signature};`,+ },+ },+ );++ return data.status;+ } catch (e) {+ throw new Error(e.response.data.detail || 'Wrong credentials or pineId');+ }}}diff --git a/src/miscRequests.js b/src/miscRequests.jsindex 852b033..b8ca27f 100644--- a/src/miscRequests.js+++ b/src/miscRequests.js@@ -1,31 +1,19 @@const os = require('os');-const https = require('https');-const request = require('./request');-const FormData = require('./FormData');+const axios = require('axios');-const PinePermManager = require('./classes/PinePermManager');const PineIndicator = require('./classes/PineIndicator');+const validateStatus = (status) => status < 500;+const indicators = ['Recommend.Other', 'Recommend.All', 'Recommend.MA'];const builtInIndicList = [];async function fetchScanData(tickers = [], type = '', columns = []) {- let { data } = await request({- method: 'POST',- hostname: 'scanner.tradingview.com',- path: `/${type}/scan`,- headers: {- 'Content-Type': 'application/json',- },- }, true, JSON.stringify({ symbols: { tickers }, columns }));-- if (!data.startsWith('{')) throw new Error('Wrong screener or symbol');-- try {- data = JSON.parse(data);- } catch (e) {- throw new Error('Can\'t parse server response');- }+ const { data } = await axios.post(`https://scanner.tradingview.com/${type}/scan`, {+ validateStatus,+ symbols: { tickers },+ columns,+ });return data;}@@ -53,40 +41,40 @@ async function fetchScanData(tickers = [], type = '', columns = []) {* }} Periods*/-/**- * @typedef {string | 'forex' | 'crypto'- * | 'america' | 'australia' | 'canada' | 'egypt'- * | 'germany' | 'india' | 'israel' | 'italy'- * | 'luxembourg' | 'poland' | 'sweden' | 'turkey'- * | 'uk' | 'vietnam'} Screener- * You can use `getScreener(exchange)` function for non-forex and non-crypto markets.- */+// /**+// * @typedef {string | 'forex' | 'crypto'+// * | 'america' | 'australia' | 'canada' | 'egypt'+// * | '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 = {- /**- * Get a screener from an exchange- * @function getScreener- * @param {string} exchange Example: BINANCE, EURONEXT, NASDAQ- * @returns {Screener}- */- getScreener(exchange) {- const e = exchange.toUpperCase();- if (['NASDAQ', 'NYSE', 'NYSE ARCA', 'OTC'].includes(e)) return 'america';- if (['ASX'].includes(e)) return 'australia';- if (['TSX', 'TSXV', 'CSE', 'NEO'].includes(e)) return 'canada';- if (['EGX'].includes(e)) return 'egypt';- if (['FWB', 'SWB', 'XETR'].includes(e)) return 'germany';- if (['BSE', 'NSE'].includes(e)) return 'india';- if (['TASE'].includes(e)) return 'israel';- if (['MIL', 'MILSEDEX'].includes(e)) return 'italy';- if (['LUXSE'].includes(e)) return 'luxembourg';- if (['NEWCONNECT'].includes(e)) return 'poland';- if (['NGM'].includes(e)) return 'sweden';- if (['BIST'].includes(e)) return 'turkey';- if (['LSE', 'LSIN'].includes(e)) return 'uk';- if (['HNX'].includes(e)) return 'vietnam';- return exchange.toLowerCase();- },+ // /**+ // * Get a screener from an exchange+ // * @function getScreener+ // * @param {string} exchange Example: BINANCE, EURONEXT, NASDAQ+ // * @returns {Screener}+ // */+ // getScreener(exchange) {+ // const e = exchange.toUpperCase();+ // if (['NASDAQ', 'NYSE', 'NYSE ARCA', 'OTC'].includes(e)) return 'america';+ // if (['ASX'].includes(e)) return 'australia';+ // if (['TSX', 'TSXV', 'CSE', 'NEO'].includes(e)) return 'canada';+ // if (['EGX'].includes(e)) return 'egypt';+ // if (['FWB', 'SWB', 'XETR'].includes(e)) return 'germany';+ // if (['BSE', 'NSE'].includes(e)) return 'india';+ // if (['TASE'].includes(e)) return 'israel';+ // if (['MIL', 'MILSEDEX'].includes(e)) return 'italy';+ // if (['LUXSE'].includes(e)) return 'luxembourg';+ // if (['NEWCONNECT'].includes(e)) return 'poland';+ // if (['NGM'].includes(e)) return 'sweden';+ // if (['BIST'].includes(e)) return 'turkey';+ // if (['LSE', 'LSIN'].includes(e)) return 'uk';+ // if (['HNX'].includes(e)) return 'vietnam';+ // return 'global';+ // },/*** Get technical analysis@@ -138,20 +126,25 @@ module.exports = {* @returns {Promise<SearchMarketResult[]>} Search results*/async searchMarket(search, filter = '') {- const { data } = await request({- host: 'symbol-search.tradingview.com',- path: `/symbol_search/?text=${search.replace(/ /g, '%20')}&type=${filter}`,- origin: 'https://www.tradingview.com',- });+ const { data } = await axios.get(+ `https://symbol-search.tradingview.com/symbol_search/?text=${search.replace(/ /g, '%20')}&type=${filter}`,+ {+ validateStatus,+ headers: {+ origin: 'https://www.tradingview.com',+ },+ },+ );return data.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)- );+ // const screener = (['forex', 'crypto'].includes(s.type)+ // ? s.type+ // : this.getScreener(exchange)+ // );+ const screener = 'global';return {id,@@ -189,17 +182,18 @@ module.exports = {async searchIndicator(search = '') {if (!builtInIndicList.length) {await Promise.all(['standard', 'candlestick', 'fundamental'].map(async (type) => {- builtInIndicList.push(...(await request({- host: 'pine-facade.tradingview.com',- path: `/pine-facade/list/?filter=${type}`,- })).data);+ const { data } = await axios.get(+ `https://pine-facade.tradingview.com/pine-facade/list/?filter=${type}`,+ { validateStatus },+ );+ builtInIndicList.push(...data);}));}- const { data } = await request({- host: 'www.tradingview.com',- path: `/pubscripts-suggest-json/?search=${search.replace(/ /g, '%20')}`,- });+ const { data } = await axios.get(+ `https://www.tradingview.com/pubscripts-suggest-json/?search=${search.replace(/ /g, '%20')}`,+ { validateStatus },+ );function norm(str = '') {return str.toUpperCase().replace(/[^A-Z]/g, '');@@ -255,16 +249,10 @@ module.exports = {async getIndicator(id, version = 'last') {const indicID = id.replace(/ |%/g, '%25');- let { data } = await request({- host: 'pine-facade.tradingview.com',- path: `/pine-facade/translate/${indicID}/${version}`,- }, true);-- try {- data = JSON.parse(data);- } catch (e) {- throw new Error(`Inexistent or unsupported indicator: '${id}'`);- }+ const { data } = await axios.get(+ `https://pine-facade.tradingview.com/pine-facade/translate/${indicID}/${version}`,+ { validateStatus },+ );if (!data.success || !data.result.metaInfo || !data.result.metaInfo.inputs) {throw new Error(`Inexistent or unsupported indicator: "${data.reason}"`);@@ -358,21 +346,20 @@ module.exports = {* @returns {Promise<User>} Token*/async loginUser(username, password, remember = true, UA = 'TWAPI/3.0') {- const formData = new FormData();- formData.append('username', username);- formData.append('password', password);- if (remember) formData.append('remember', 'on');-- const { data, cookies } = await request({- method: 'POST',- host: 'www.tradingview.com',- path: '/accounts/signin/',- headers: {- referer: 'https://www.tradingview.com',- 'Content-Type': `multipart/form-data; boundary=${formData.boundary}`,- 'User-agent': `${UA} (${os.version()}; ${os.platform()}; ${os.arch()})`,+ const { data, headers } = await axios.post(+ 'https://www.tradingview.com/accounts/signin/',+ `username=${username}&password=${password}${remember ? '&remember=on' : ''}`,+ {+ validateStatus,+ headers: {+ referer: 'https://www.tradingview.com',+ 'Content-Type': 'application/x-www-form-urlencoded',+ 'User-agent': `${UA} (${os.version()}; ${os.platform()}; ${os.arch()})`,+ },},- }, false, formData.toString());+ );++ const cookies = headers['set-cookie'];if (data.error) throw new Error(data.error);@@ -409,43 +396,36 @@ module.exports = {* @returns {Promise<User>} Token*/async getUser(session, signature = '', location = 'https://www.tradingview.com/') {- return new Promise((cb, err) => {- https.get(location, {- headers: { cookie: `sessionid=${session}${signature ? `;sessionid_sign=${signature};` : ''}` },- }, (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.getUser(session, signature, res.headers.location));- return;- }- if (rs.includes('auth_token')) {- cb({- id: /"id":([0-9]{1,10}),/.exec(rs)[1],- username: /"username":"(.*?)"/.exec(rs)[1],- firstName: /"first_name":"(.*?)"/.exec(rs)[1],- lastName: /"last_name":"(.*?)"/.exec(rs)[1],- reputation: parseFloat(/"reputation":(.*?),/.exec(rs)[1] || 0),- following: parseFloat(/,"following":([0-9]*?),/.exec(rs)[1] || 0),- followers: parseFloat(/,"followers":([0-9]*?),/.exec(rs)[1] || 0),- notifications: {- following: parseFloat(/"notification_count":\{"following":([0-9]*),/.exec(rs)[1] || 0),- user: parseFloat(/"notification_count":\{"following":[0-9]*,"user":([0-9]*)/.exec(rs)[1] || 0),- },- session,- signature,- sessionHash: /"session_hash":"(.*?)"/.exec(rs)[1],- privateChannel: /"private_channel":"(.*?)"/.exec(rs)[1],- authToken: /"auth_token":"(.*?)"/.exec(rs)[1],- joinDate: new Date(/"date_joined":"(.*?)"/.exec(rs)[1] || 0),- });- } else err(new Error('Wrong or expired sessionid/signature'));- });-- res.on('error', err);- }).end();+ const { data } = await axios.get(location, {+ validateStatus,+ headers: {+ cookie: `sessionid=${session}${signature ? `;sessionid_sign=${signature};` : ''}`,+ },});++ if (data.includes('auth_token')) {+ return {+ id: /"id":([0-9]{1,10}),/.exec(data)?.[1],+ username: /"username":"(.*?)"/.exec(data)?.[1],+ firstName: /"first_name":"(.*?)"/.exec(data)?.[1],+ lastName: /"last_name":"(.*?)"/.exec(data)?.[1],+ reputation: parseFloat(/"reputation":(.*?),/.exec(data)?.[1] || 0),+ following: parseFloat(/,"following":([0-9]*?),/.exec(data)?.[1] || 0),+ followers: parseFloat(/,"followers":([0-9]*?),/.exec(data)?.[1] || 0),+ notifications: {+ following: parseFloat(/"notification_count":\{"following":([0-9]*),/.exec(data)?.[1] || 0),+ user: parseFloat(/"notification_count":\{"following":[0-9]*,"user":([0-9]*)/.exec(data)?.[1] || 0),+ },+ session,+ signature,+ sessionHash: /"session_hash":"(.*?)"/.exec(data)?.[1],+ privateChannel: /"private_channel":"(.*?)"/.exec(data)?.[1],+ authToken: /"auth_token":"(.*?)"/.exec(data)?.[1],+ joinDate: new Date(/"date_joined":"(.*?)"/.exec(data)?.[1] || 0),+ };+ }++ throw new Error('Wrong or expired sessionid/signature');},/**@@ -456,44 +436,29 @@ module.exports = {* @returns {Promise<SearchIndicatorResult[]>} Search results*/async getPrivateIndicators(session, signature = '') {- return new Promise((cb, err) => {- https.get('https://pine-facade.tradingview.com/pine-facade/list?filter=saved', {- headers: { cookie: `sessionid=${session}${signature ? `;sessionid_sign=${signature};` : ''}` },- }, (res) => {- let rs = '';- res.on('data', (d) => { rs += d; });- res.on('end', async () => {- try {- rs = JSON.parse(rs);- } catch (error) {- err(new Error('Can\'t parse private indicator list'));- return;- }-- cb(rs.map((ind) => ({- id: ind.scriptIdPart,- version: ind.version,- name: ind.scriptName,- author: {- id: -1,- username: '@ME@',- },- image: ind.imageUrl,- access: 'private',- source: ind.scriptSource,- type: (ind.extra && ind.extra.kind) ? ind.extra.kind : 'study',- get() {- return module.exports.getIndicator(ind.scriptIdPart, ind.version);- },- getManager() {- return new PinePermManager(ind.scriptIdPart);- },- })));- });-- res.on('error', err);- }).end();+ const { data } = await axios.get('https://pine-facade.tradingview.com/pine-facade/list?filter=saved', {+ validateStatus,+ headers: {+ cookie: `sessionid=${session}${signature ? `;sessionid_sign=${signature};` : ''}`,+ },});++ return data.map((ind) => ({+ id: ind.scriptIdPart,+ version: ind.version,+ name: ind.scriptName,+ author: {+ id: -1,+ username: '@ME@',+ },+ image: ind.imageUrl,+ access: 'private',+ source: ind.scriptSource,+ type: (ind.extra && ind.extra.kind) ? ind.extra.kind : 'study',+ get() {+ return module.exports.getIndicator(ind.scriptIdPart, ind.version);+ },+ }));},/**@@ -501,6 +466,7 @@ module.exports = {* @typedef {Object} UserCredentials* @prop {number} id User ID* @prop {string} session User session ('sessionid' cookie)+ * @prop {string} [signature] User session signature ('sessionid_sign' cookie)*//**@@ -511,16 +477,23 @@ module.exports = {* @returns {Promise<string>} Token*/async getChartToken(layout, credentials = {}) {- const creds = credentials.id && credentials.session;- const userID = creds ? credentials.id : -1;- const session = creds ? credentials.session : null;- const signature = creds ? credentials.signature : null;-- const { data } = await request({- host: 'www.tradingview.com',- path: `/chart-token/?image_url=${layout}&user_id=${userID}`,- headers: { cookie: session ? `sessionid=${session}${signature ? `;sessionid_sign=${signature};` : ''}` : '' },- });+ const { id, session, signature } = (+ credentials.id && credentials.session+ ? credentials+ : { id: -1, session: null, signature: null }+ );++ const { data } = await axios.get(+ `https://www.tradingview.com/chart-token/?image_url=${layout}&user_id=${id}`,+ {+ validateStatus,+ headers: {+ cookie: session+ ? `sessionid=${session}${signature ? `;sessionid_sign=${signature};` : ''}`+ : '',+ },+ },+ );if (!data.token) throw new Error('Wrong layout or credentials');@@ -558,18 +531,21 @@ module.exports = {* @param {number} [chartID] Chart ID* @returns {Promise<Drawing[]>} Drawings*/- async getDrawings(layout, symbol = '', credentials = {}, chartID = 1) {+ async getDrawings(layout, symbol = '', credentials = {}, chartID = '_shared') {const chartToken = await module.exports.getChartToken(layout, credentials);- const creds = credentials.id && credentials.session;- const session = creds ? credentials.session : null;- const signature = creds ? credentials.signature : null;-- const { data } = await request({- host: 'charts-storage.tradingview.com',- path: `/charts-storage/layout/${layout}/sources?chart_id=${chartID- }&jwt=${chartToken}${symbol ? `&symbol=${symbol}` : ''}`,- headers: { cookie: session ? `sessionid=${session}${signature ? `;sessionid_sign=${signature};` : ''}` : '' },- });++ const { data } = await axios.get(+ `https://charts-storage.tradingview.com/charts-storage/get/layout/${+ layout+ }/sources?chart_id=${+ chartID+ }&jwt=${+ chartToken+ }${+ (symbol ? `&symbol=${symbol}` : '')+ }`,+ { validateStatus },+ );if (!data.payload) throw new Error('Wrong layout, user credentials, or chart id.');diff --git a/src/request.js b/src/request.jsdeleted file mode 100644index fa6e057..0000000--- a/src/request.js+++ /dev/null@@ -1,37 +0,0 @@-const https = require('https');--/**- * @param {https.RequestOptions} options HTTPS Request options- * @param {boolean} [raw] Get raw or JSON data- * @param {string} [content] Request body content- * @returns {Promise<{ data: (string | object | array), cookies: string[] }>} Result- */-function request(options = {}, raw = false, content = '') {- return new Promise((cb, err) => {- const req = https.request(options, (res) => {- let data = '';- res.on('data', (c) => { data += c; });- res.on('end', () => {- if (raw) {- cb({ data, cookies: res.headers['set-cookie'] });- return;- }-- try {- data = JSON.parse(data);- } catch (error) {- console.log(data);- err(new Error('Can\'t parse server response'));- return;- }-- cb({ data, cookies: res.headers['set-cookie'] });- });- });-- req.on('error', err);- req.end(content);- });-}--module.exports = request;diff --git a/test.js b/test.jsdeleted file mode 100644index 72db92d..0000000--- a/test.js+++ /dev/null@@ -1,70 +0,0 @@-/* eslint-disable no-continue */-/* eslint-disable no-await-in-loop */-/* eslint-disable import/no-dynamic-require */-/* eslint-disable no-restricted-syntax */-/* eslint-disable global-require */--const fs = require('fs');-require('@mathieuc/console')(- '§', // Character you want to use (defaut: '§')- true, // Active timestamp (defaut: false)-);--const TESTS = {};--function err(name) {- return (...msg) => {- TESTS[name].errors += 1;- console.error('§30§101 > §0', ...msg);- };-}--function warn(name) {- return (...msg) => {- TESTS[name].warnings += 1;- console.warn('§30§103 > §0', ...msg);- };-}--function log() {- return (...msg) => console.log('§30§107 > §0', ...msg);-}--function success() {- return (...msg) => console.info('§30§102 > §0', ...msg);-}--(async () => {- console.info('§90§30§104 ==== Starting tests ==== §0');-- for (const file of fs.readdirSync('./tests').filter((f) => f.endsWith('.js'))) {- if (process.argv[2] && !file.startsWith(process.argv[2])) continue;- const test = require(`./tests/${file}`);- const name = file.replace(/\.js/g, '');- TESTS[name] = { errors: 0, warnings: 0 };- console.log(`§90§30§107 ${name}`);- await new Promise((cb) => test(log(), success(), warn(name), err(name), cb));- }-- console.info('§90§30§104 ==== ALL TESTS DONE ==== §0\n');-- let errored = false;-- Object.keys(TESTS).forEach((t) => {- let color = '2';- if (TESTS[t].warnings) color = '3';- if (TESTS[t].errors) {- color = '1';- errored = true;- }-- console.info(`§90§30§10${color} ${t} §0 §91E§0: ${TESTS[t].errors}§0 §93W§0: ${TESTS[t].warnings}`);- });-- process.exit(errored ? 1 : 0);-})();--setTimeout(() => {- console.log('§30§101 TIMEOUT §0');- throw new Error('Timeout');-}, 60000);diff --git a/tests/01. Search.js b/tests/01. Search.jsdeleted file mode 100644index 4e3aca9..0000000--- a/tests/01. Search.js+++ /dev/null@@ -1,17 +0,0 @@-const TradingView = require('../main');--module.exports = async (log, success, warn, err, cb) => {- log('Searching market: \'BINANCE:\'');- const markets = await TradingView.searchMarket('BINANCE:');- success('Found', markets.length, 'markets');-- log('Searching indicator: \'RSI\'');- const indicators = await TradingView.searchIndicator('RSI');- success('Found', indicators.length, 'indicators');-- if (markets.length < 10 || indicators.length < 10) {- err('Not enough results');- }-- cb();-};diff --git a/tests/02. QuoteSession.js b/tests/02. QuoteSession.jsdeleted file mode 100644index 8acee93..0000000--- a/tests/02. QuoteSession.js+++ /dev/null@@ -1,51 +0,0 @@-const TradingView = require('../main');--module.exports = (log, success, warn, err, cb) => {- const client = new TradingView.Client();-- client.onError((...error) => {- err('Client error', ...error);- });-- const quoteSession = new client.Session.Quote({- fields: 'all',- });-- const BTC = new quoteSession.Market('BTCEUR');-- BTC.onLoaded(() => {- success('BTCEUR LOADED');- });-- const keys = [- 'volume', 'update_mode', 'type', 'timezone',- 'short_name', 'rtc_time', 'rtc', 'rchp', 'ch',- 'rch', 'provider_id', 'pro_name', 'pricescale',- 'prev_close_price', 'original_name', 'lp',- 'open_price', 'minmove2', 'minmov', 'lp_time',- 'low_price', 'is_tradable', 'high_price',- 'fractional', 'exchange', 'description',- 'current_session', 'currency_code', 'chp',- 'currency-logoid', 'base-currency-logoid',- ];-- BTC.onData(async (data) => {- const rsKeys = Object.keys(data);- success('BTCEUR DATA');- if (rsKeys.length <= 2) return;-- keys.forEach((k) => {- if (!rsKeys.includes(k)) {- err(`Missing '${k}' key in`, rsKeys);- }- });-- quoteSession.delete();- await client.end();- cb();- });-- BTC.onError((...error) => {- err('BTCEUR ERROR:', error);- });-};diff --git a/tests/03. SimpleChart.js b/tests/03. SimpleChart.jsdeleted file mode 100644index c2c6fd0..0000000--- a/tests/03. SimpleChart.js+++ /dev/null@@ -1,59 +0,0 @@-const TradingView = require('../main');--module.exports = async (log, success, warn, err, cb) => {- const client = new TradingView.Client();-- client.onError((...error) => {- err('Client error', error);- });-- const chart = new client.Session.Chart();-- chart.setMarket('BINANCE:BTCEUR', { // Set the market- timeframe: 'D',- });-- chart.onError((...error) => {- err('Chart error', error);- });-- chart.onSymbolLoaded(() => { // When the symbol is successfully loaded- success(`Market "${chart.infos.description}" loaded !`);- });-- // Wait 3 seconds and set the market to BINANCE:ETHEUR- setTimeout(() => {- log('Setting market to BINANCE:ETHEUR...');- chart.setMarket('BINANCE:ETHEUR', {- timeframe: 'D',- });- }, 2000);-- // Wait 4 seconds and set the timeframe to 15 minutes- setTimeout(() => {- log('Setting timeframe to 15 minutes...');- chart.setSeries('15');- }, 3000);-- // Wait 5 seconds and set the chart type to "Heikin Ashi"- setTimeout(() => {- log('Setting the chart type to "Heikin Ashi"...');- chart.setMarket('BINANCE:ETHEUR', {- timeframe: 'D',- type: 'HeikinAshi',- });- }, 4000);-- // Wait 7 seconds and close the chart- setTimeout(() => {- log('Closing the chart...');- chart.delete();- }, 5000);-- // Wait 8 seconds and close the client- setTimeout(async () => {- log('Closing the client...');- await client.end();- cb();- }, 6000);-};diff --git a/tests/04. Indicators.js b/tests/04. Indicators.jsdeleted file mode 100644index 82bbfc7..0000000--- a/tests/04. Indicators.js+++ /dev/null@@ -1,96 +0,0 @@-const TradingView = require('../main');--module.exports = async (log, success, warn, err, cb) => {- const client = new TradingView.Client();-- client.onError((...error) => {- err('Client error', error);- });-- const chart = new client.Session.Chart();- chart.setMarket('BINANCE:BTCEUR', {- timeframe: '60',- });-- chart.onError((...error) => {- err('Chart error', error);- });-- TradingView.getIndicator('STD;Supertrend%Strategy').then((indicator) => {- indicator.setOption('commission_type', 'percent');- indicator.setOption('commission_value', 0);- indicator.setOption('initial_capital', 25000);- indicator.setOption('default_qty_value', 20);- indicator.setOption('default_qty_type', 'percent_of_equity');- indicator.setOption('currency', 'EUR');- indicator.setOption('pyramiding', 10);-- const SuperTrend = new chart.Study(indicator);-- SuperTrend.onError((...error) => {- err('SuperTrend error', error[0]);- });-- let QTY = 10;-- SuperTrend.onUpdate(async () => {- // MarketCipher B is a strategy so it sends a strategy report- const perfReport = SuperTrend.strategyReport.performance;-- success('Performances:', {- total: {- trades: perfReport.all.totalTrades,- perf: `${Math.round(perfReport.all.netProfitPercent * 10000) / 100} %`,- },- buy: {- trades: perfReport.long.totalTrades,- perf: `${Math.round(perfReport.long.netProfitPercent * 10000) / 100} %`,- },- sell: {- trades: perfReport.short.totalTrades,- perf: `${Math.round(perfReport.short.netProfitPercent * 10000) / 100} %`,- },- });-- if (QTY >= 50) {- SuperTrend.remove();- chart.delete();- await client.end();- cb();- return;- }-- QTY += 10;- log('TRY WITH', QTY, '%');- setTimeout(() => {- indicator.setOption('default_qty_value', QTY);- SuperTrend.setIndicator(indicator);- }, 1000);- });- });-- TradingView.getIndicator('PUB;uA35GeckoTA2EfgI63SD2WCSmca4njxp').then((indicator) => {- indicator.setOption('Show_WT_Hidden_Divergences', true);- indicator.setOption('Show_Stoch_Regular_Divergences', true);- indicator.setOption('Show_Stoch_Hidden_Divergences', true);-- const CipherB = new chart.Study(indicator);-- CipherB.onError((...error) => {- err('MarketCipher B error:', error[0]);- });-- CipherB.onUpdate(() => {- const last = CipherB.periods[0];- // MarketCipher B is not a strategy so it only sends plots values- success('MarketCipher B last values:', {- VWAP: Math.round(last.VWAP * 1000) / 1000,- moneyFlow: (last.RSIMFIArea >= 0) ? 'POSITIVE' : 'NEGATIVE',- buyCircle: last.Buy_and_sell_circle && last.VWAP > 0,- sellCircle: last.Buy_and_sell_circle && last.VWAP < 0,- });-- CipherB.remove();- });- });-};diff --git a/tests/05. BuiltInIndicator.js b/tests/05. BuiltInIndicator.jsdeleted file mode 100644index d35fa2d..0000000--- a/tests/05. BuiltInIndicator.js+++ /dev/null@@ -1,39 +0,0 @@-const TradingView = require('../main');--module.exports = async (log, success, warn, err, cb) => {- const client = new TradingView.Client();-- client.onError((...error) => {- err('Client error', error);- });-- const chart = new client.Session.Chart();- chart.setMarket('BINANCE:BTCEUR', {- timeframe: '60',- });-- chart.onError((...error) => {- err('Chart error', error);- });-- const volumeProfile = new TradingView.BuiltInIndicator('VbPFixed@tv-basicstudies-139!');-- volumeProfile.setOption('first_bar_time', Date.now() - 10 ** 8);-- const VOL = new chart.Study(volumeProfile);- VOL.onUpdate(async () => {- VOL.graphic.horizHists- .filter((h) => h.lastBarTime === 0) // We only keep recent volume infos- .sort((a, b) => b.priceHigh - a.priceHigh)- .forEach((h) => {- success(- `~ ${Math.round((h.priceHigh + h.priceLow) / 2)} € :`,- `${'_'.repeat(h.rate[0] / 3)}${'_'.repeat(h.rate[1] / 3)}`,- );- });-- chart.delete();- await client.end();- cb();- });-};diff --git a/tests/06. FakeReplayMode.js b/tests/06. FakeReplayMode.jsdeleted file mode 100644index ae5e177..0000000--- a/tests/06. FakeReplayMode.js+++ /dev/null@@ -1,57 +0,0 @@-const TradingView = require('../main');--module.exports = async (log, success, warn, err, cb) => {- const client = new TradingView.Client();-- client.onError((...error) => {- err('Client error', error);- });-- const chart = new client.Session.Chart();- chart.setMarket('BINANCE:BTCEUR', {- timeframe: 'D',- range: -1,- to: Math.round(Date.now() / 1000) - 86400 * 7,- });-- chart.onError((...error) => {- err('Chart error', error);- });-- let interval = NaN;- let consec = 1;- let lastTime = 0;-- chart.onUpdate(async () => {- const times = chart.periods.map((p) => p.time);-- if (lastTime === times[0]) {- consec += 1;- warn(`Same lastTime ${lastTime}, ${consec} times in a row`);- } else consec = 1;- [lastTime] = times;-- if (consec >= 10) {- chart.delete();- await client.end();- cb();- }-- const intrval = times[0] - times[1];- if (Number.isNaN(interval) && times.length >= 2) interval = intrval;-- if (!Number.isNaN(interval) && interval !== intrval) {- err(`Wrong interval: ${intrval} (should be ${interval})`);- }-- log('Next ->', times[0]);-- if ((times[0] + 86400) * 1000 > Date.now()) {- chart.delete();- await client.end();- cb();- }-- chart.fetchMore(-1);- });-};diff --git a/tests/07. ReplayMode.js b/tests/07. ReplayMode.jsdeleted file mode 100644index 7043f5c..0000000--- a/tests/07. ReplayMode.js+++ /dev/null@@ -1,49 +0,0 @@-const TradingView = require('../main');--module.exports = async (log, success, warn, err, cb) => {- const client = new TradingView.Client();-- client.onError((...error) => {- err('Client error', error);- });-- const chart = new client.Session.Chart();- chart.setMarket('BINANCE:BTCEUR', {- timeframe: 'D',- replay: Math.round(Date.now() / 1000) - 86400 * 10,- range: 1,- });-- chart.onError((...error) => {- err('Chart error', error);- });-- let finished = false;- async function step() {- log('Next');- await chart.replayStep(1);- if (!finished) step();- }-- chart.onReplayLoaded(async () => {- log('START REPLAY MODE');- await chart.replayStart(200);-- setTimeout(async () => {- await chart.replayStop();- log('STOP REPLAY MODE');- step();- }, 1000);- });-- chart.onReplayPoint((p) => {- success('Point ->', p);- });-- chart.onReplayEnd(async () => {- finished = true;- chart.delete();- await client.end();- cb();- });-};diff --git a/tests/08. CustomChartTypes.js b/tests/08. CustomChartTypes.jsdeleted file mode 100644index 5de689a..0000000--- a/tests/08. CustomChartTypes.js+++ /dev/null@@ -1,113 +0,0 @@-const TradingView = require('../main');--module.exports = async (log, success, warn, err, cb) => {- const client = new TradingView.Client();-- client.onError((...error) => {- err('Client error', error);- });-- const chart = new client.Session.Chart();-- chart.onError((...error) => {- err('Chart error', error);- });-- /* (0s) Heikin Ashi chart */- setTimeout(() => {- log('Setting chart type to: HeikinAshi');-- chart.setMarket('BINANCE:BTCEUR', {- type: 'HeikinAshi',- timeframe: 'D',- });- }, 0);-- /* (1s) Renko chart */- setTimeout(() => {- log('Setting chart type to: Renko');-- chart.setMarket('BINANCE:BTCEUR', {- type: 'Renko',- timeframe: 'D',- inputs: {- source: 'close',- sources: 'Close',- boxSize: 3,- style: 'ATR',- atrLength: 14,- wicks: true,- },- });- }, 1000);-- /* (2s) Line Break chart */- setTimeout(() => {- log('Setting chart type to: LineBreak');-- chart.setMarket('BINANCE:BTCEUR', {- type: 'LineBreak',- timeframe: 'D',- inputs: {- source: 'close',- lb: 3,- },- });- }, 2000);-- /* (3s) Kagi chart */- setTimeout(() => {- log('Setting chart type to: Kagi');-- chart.setMarket('BINANCE:BTCEUR', {- type: 'Kagi',- timeframe: 'D',- inputs: {- source: 'close',- style: 'ATR',- atrLength: 14,- reversalAmount: 1,- },- });- }, 3000);-- /* (4s) Point & Figure chart */- setTimeout(() => {- log('Setting chart type to: PointAndFigure');-- chart.setMarket('BINANCE:BTCEUR', {- type: 'PointAndFigure',- timeframe: 'D',- inputs: {- sources: 'Close',- reversalAmount: 3,- boxSize: 1,- style: 'ATR',- atrLength: 14,- oneStepBackBuilding: false,- },- });- }, 4000);-- /* (5s) Range chart */- setTimeout(() => {- log('Setting chart type to: Range');-- chart.setMarket('BINANCE:BTCEUR', {- type: 'Range',- timeframe: 'D',- inputs: {- range: 1,- phantomBars: false,- },- });- }, 5000);-- /* (6s) Delete chart, close client */- setTimeout(async () => {- success('Closing client...');- chart.delete();- await client.end();- cb();- }, 6000);-};diff --git a/tests/09. AllErrors.js b/tests/09. AllErrors.jsdeleted file mode 100644index 6611d79..0000000--- a/tests/09. AllErrors.js+++ /dev/null@@ -1,184 +0,0 @@-const TradingView = require('../main');--module.exports = async (log, success, warn, err, cb) => {- const client = new TradingView.Client(); // Creates a websocket client-- const tests = [- (next) => { /* Testing "Credentials error" */- log('Testing "Credentials error" error:');-- const client2 = new TradingView.Client({- token: 'FAKE_CREDENTIALS', // Set wrong credentials- });-- client2.onError((...error) => {- success('=> Client error:', error);- client2.end();- next();- });- },-- (next) => { /* Testing "Invalid symbol" */- log('Testing "Invalid symbol" error:');-- const chart = new client.Session.Chart();- chart.onError((...error) => { // Listen for errors- success('=> Chart error:', error);- chart.delete();- next();- });-- chart.setMarket('XXXXX'); // Set a wrong market- },-- (next) => { /* Testing "Invalid timezone" */- log('Testing "Invalid timezone" error:');-- const chart = new client.Session.Chart();- chart.onError((...error) => { // Listen for errors- success('=> Chart error:', error);- next();- });-- chart.setMarket('BINANCE:BTCEUR'); // Set a market- chart.setTimezone('Nowhere/Nowhere'); // Set a fake timezone- },-- (next) => { /* Testing "Custom timeframe" */- log('Testing "Custom timeframe" error:');-- const chart = new client.Session.Chart();- chart.onError((...error) => { // Listen for errors- success('=> Chart error:', error);- 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 account- */- });- },-- (next) => { /* Testing "Invalid timeframe" */- log('Testing "Invalid timeframe" error:');-- const chart = new client.Session.Chart();- chart.onError((...error) => { // Listen for errors- success('=> Chart error:', error);- next();- });-- chart.setMarket('BINANCE:BTCEUR', { // Set a market- timeframe: 'XX', // Set a wrong timeframe- });- },-- (next) => { /* Testing "Study not auth" */- log('Testing "Study not auth" error:');-- const chart = new client.Session.Chart();- chart.onError((...error) => { // Listen for errors- success('=> Chart error:', error);- next();- });-- chart.setMarket('BINANCE:BTCEUR', { // Set a market- timeframe: '15',- type: 'Renko',- });-- chart.onUpdate(() => {- log('DATA', chart.periods[0]);- });- },-- (next) => { /* Testing "Set the market before" */- log('Testing "Set the market before..." error:');-- const chart = new client.Session.Chart();- chart.onError((...error) => { // Listen for errors- success('=> Chart error:', error);- chart.delete();- next();- });-- chart.setSeries('15'); // Set series before setting the market- },-- (next) => { /* Testing "Inexistent indicator" */- log('Testing "Inexistent indicator" error:');-- TradingView.getIndicator('STD;XXXXXXX')- .catch((error) => {- success('=> API error:', [error.message]);- next();- });- },-- async (next) => { /* Testing "Invalid value" */- log('Testing "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((...error) => {- success('=> Study error:', error);- chart.delete();- next();- });- },-- async (next) => { /* Testing "Wrong or expired sessionid/signature" using getUser method */- log('Testing "Wrong or expired sessionid/signature" error using getUser method:');-- if (!process.env.SESSION) {- warn('=> Skipping test because no sessionid/signature was provided');- next();- return;- }-- try {- await TradingView.getUser(process.env.SESSION);- err('=> User found !');- } catch (error) {- success('=> User not found:', error);- next();- }- },-- async (next) => { /* Testing "Wrong or expired sessionid/signature" using client */- log('Testing "Wrong or expired sessionid/signature" error using client:');-- if (!process.env.SESSION) {- warn('=> Skipping test because no sessionid/signature was provided');- next();- return;- }-- log('Creating a new client...');- const client2 = new TradingView.Client({- token: process.env.SESSION,- });-- client2.onError((...error) => {- success('=> Client error:', error);- client2.end();- next();- });- },- ];-- (async () => {- for (const t of tests) await new Promise(t);- success(`Crashtests ${tests.length}/${tests.length} done !`);- cb();- })();-};diff --git a/tests/10. Authenticated.js b/tests/10. Authenticated.jsdeleted file mode 100644index 2ccecb9..0000000--- a/tests/10. Authenticated.js+++ /dev/null@@ -1,101 +0,0 @@-const TradingView = require('../main');--const wait = (ms) => new Promise((cb) => { setTimeout(cb, ms); });--module.exports = async (log, success, warn, err, cb) => {- if (!process.env.SESSION || !process.env.SIGNATURE) {- warn('No sessionid/signature was provided');- cb();- return;- }-- log('Getting user info');-- const userInfos = await TradingView.getUser(process.env.SESSION, process.env.SIGNATURE);- if (userInfos && userInfos.id) {- success('User info:', {- id: userInfos.id,- username: userInfos.username,- firstName: userInfos.firstName,- lastName: userInfos.lastName,- following: userInfos.following,- followers: userInfos.followers,- notifications: userInfos.notifications,- joinDate: userInfos.joinDate,- });- } else err('Get user error. Result:', userInfos);-- await wait(1000);-- log('Getting user indicators');- const userIndicators = await TradingView.getPrivateIndicators(process.env.SESSION);-- if (userIndicators) {- if (userIndicators.length === 0) warn('No private indicator found');- else success('User indicators:', userIndicators.map((i) => i.name));- } else err('Get indicators error. Result:', userIndicators);-- await wait(1000);-- log('Creating logged client');- const client = new TradingView.Client({- token: process.env.SESSION,- signature: process.env.SIGNATURE,- });-- client.onError((...error) => {- err('Client error', error);- });-- const chart = new client.Session.Chart();- chart.onError((...error) => {- err('Chart error', error);- });-- log('Setting market to BINANCE:BTCEUR...');- chart.setMarket('BINANCE:BTCEUR', { timeframe: 'D' });-- const checked = new Set();- async function check(item) {- checked.add(item);- log('Checked:', [...checked], `(${checked.size}/${userIndicators.length + 1})`);- if (checked.size < userIndicators.length + 1) return;-- log('Closing client...');- chart.delete();- await client.end();- success('Client closed');- cb();- }-- chart.onUpdate(async () => {- success('Market data:', {- name: chart.infos.pro_name,- description: chart.infos.short_description,- exchange: chart.infos.exchange,- price: chart.periods[0].close,- });-- await check(Symbol.for('PRICE'));- });-- await wait(1000);-- log('Loading indicators...');- for (const indic of userIndicators) {- const privateIndic = await indic.get();- log(`[${indic.name}] Loading indicator...`);-- const indicator = new chart.Study(privateIndic);-- indicator.onReady(() => {- success(`[${indic.name}] Indicator loaded !`);- });-- indicator.onUpdate(async () => {- success(`[${indic.name}] Last plot:`, indicator.periods[0]);- await check(indic.id);- });- }- log('Indicators loaded !');-};diff --git a/tests/allErrors.test.ts b/tests/allErrors.test.tsindex 08731dd..ea78e85 100644--- a/tests/allErrors.test.ts+++ b/tests/allErrors.test.ts@@ -1,6 +1,9 @@import { describe, it, expect } from 'vitest';import TradingView from '../main';+const token = process.env.SESSION as string;+const signature = process.env.SIGNATURE as string;+describe('AllErrors', () => {const waitForError = (instance: any) => new Promise<string[]>((resolve) => {instance.onError((...error: string[]) => {@@ -121,7 +124,7 @@ describe('AllErrors', () => {expect(error).toBeDefined();expect(error[0]).toBe('Series error:');- expect(error[1]).toBe('study_not_auth:BarSetRenko@tv-prostudies-66');+ expect(error[1]).toMatch(/study_not_auth:BarSetRenko@tv-prostudies-\d+/);expect(error.length).toBe(2);});@@ -184,16 +187,13 @@ describe('AllErrors', () => {console.log('OK');});- it('throws an error when getting user data without signature', async () => {+ it.skipIf(+ !token || !signature,+ )('throws an error when getting user data without signature', async () => {console.log('Testing "Wrong or expired sessionid/signature" error using getUser method:');- if (!process.env.SESSION || !process.env.SIGNATURE) {- console.log('=> Skipping test because SESSION env var is not set');- return;- }-console.log('Trying with signaure');- const userInfo = await TradingView.getUser(process.env.SESSION, process.env.SIGNATURE);+ const userInfo = await TradingView.getUser(token, signature);console.log('Result:', {id: userInfo.id,@@ -211,23 +211,18 @@ describe('AllErrors', () => {console.log('Trying without signaure');expect(- TradingView.getUser(process.env.SESSION),+ TradingView.getUser(token),).rejects.toThrow('Wrong or expired sessionid/signature');console.log('OK');});- it('throws an error when creating an authenticated client without signature', async () => {+ it.skipIf(+ !token || !signature,+ )('throws an error when creating an authenticated client without signature', async () => {console.log('Testing "Wrong or expired sessionid/signature" error using client:');- if (!process.env.SESSION || !process.env.SIGNATURE) {- console.log('=> Skipping test because SESSION env var is not set');- return;- }-- const client = new TradingView.Client({- token: process.env.SESSION,- });+ const client = new TradingView.Client({ token });const error = await waitForError(client);console.log('=> Client error:', error);diff --git a/tests/authenticated.test.ts b/tests/authenticated.test.tsindex 7c4aa0d..dd966c9 100644--- a/tests/authenticated.test.ts+++ b/tests/authenticated.test.ts@@ -2,19 +2,14 @@ import { describe, it, expect } from 'vitest';import TradingView from '../main';import utils from './utils';-describe('Authenticated actions', () => {+const token = process.env.SESSION as string;+const signature = process.env.SIGNATURE as string;++describe.skipIf(!token || !signature)('Authenticated actions', () => {it('gets user info', async () => {console.log('Testing getUser method');- if (!process.env.SESSION || !process.env.SIGNATURE) {- console.log('=> Skipping test because SESSION env var is not set');- return;- }-- const userInfo = await TradingView.getUser(- process.env.SESSION as string,- process.env.SIGNATURE,- );+ const userInfo = await TradingView.getUser(token, signature);console.log('User:', {id: userInfo.id,@@ -39,8 +34,8 @@ describe('Authenticated actions', () => {expect(userInfo.notifications.user).toBeDefined();expect(userInfo.joinDate).toBeDefined();- expect(userInfo.session).toBe(process.env.SESSION);- expect(userInfo.signature).toBe(process.env.SIGNATURE);+ expect(userInfo.session).toBe(token);+ expect(userInfo.signature).toBe(signature);});const userIndicators: any[] = [];@@ -48,12 +43,7 @@ describe('Authenticated actions', () => {it('gets user indicators', async () => {console.log('Testing getPrivateIndicators method');- if (!process.env.SESSION || !process.env.SIGNATURE) {- console.log('=> Skipping test because SESSION env var is not set');- return;- }-- userIndicators.push(...await TradingView.getPrivateIndicators(process.env.SESSION));+ userIndicators.push(...await TradingView.getPrivateIndicators(token));console.log('Indicators:', userIndicators.map((i) => i.name));expect(userIndicators.length).toBeGreaterThan(0);@@ -61,11 +51,7 @@ describe('Authenticated actions', () => {it('creates a chart with all user indicators', async () => {console.log('Creating logged client');- const client = new TradingView.Client({- token: process.env.SESSION,- signature: process.env.SIGNATURE,- });-+ const client = new TradingView.Client({ token, signature });const chart = new client.Session.Chart();console.log('Setting market to BINANCE:BTCEUR...');diff --git a/tests/customChartTypes.test.ts b/tests/customChartTypes.test.tsindex db26a97..e2af432 100644--- a/tests/customChartTypes.test.ts+++ b/tests/customChartTypes.test.ts@@ -58,7 +58,6 @@ describe('CustomChartTypes', () => {) await utils.wait(100);expect(chart.infos.full_name).toBe('BINANCE:ETHEUR');- expect(chart.periods.length).toBe(100);});it('sets chart type to LineBreak', async () => {@@ -79,10 +78,6 @@ describe('CustomChartTypes', () => {) await utils.wait(100);expect(chart.infos.full_name).toBe('BINANCE:BTCEUR');- expect(chart.periods.length).toBe(100);- expect(- utils.calculateTimeGap(chart.periods),- ).toBe(86400);});it('sets chart type to Kagi', async () => {diff --git a/tests/search.test.ts b/tests/search.test.tsindex f35147b..652bf39 100644--- a/tests/search.test.ts+++ b/tests/search.test.ts@@ -18,3 +18,23 @@ describe('Search functions', () => {expect(indicators.length).toBeGreaterThan(10);});});++describe('Technical Analysis', () => {+ it('gets TA for BINANCE:BTCUSD', async () => {+ checkTA(await (await searchMarket('BINANCE:BTCUSD'))[0].getTA());+ });++ it('gets TA for NASDAQ:AAPL', async () => {+ checkTA(await (await searchMarket('NASDAQ:AAPL'))[0].getTA());+ });++ function checkTA(ta = {}) {+ expect(ta).toBeDefined();+ for (const period of ['1', '5', '15', '60', '240', '1D', '1W', '1M']) {+ expect(ta[period]).toBeDefined();+ expect(ta[period].Other).toBeDefined();+ expect(ta[period].All).toBeDefined();+ expect(ta[period].MA).toBeDefined();+ }+ }+});diff --git a/vite.config.ts b/vite.config.tsnew file mode 100644index 0000000..d517dc8--- /dev/null+++ b/vite.config.ts@@ -0,0 +1,7 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ setupFiles: 'dotenv/config',+ },+});