Skip to content

📈 Get real-time stocks from TradingView

Create tests

Mathieu Colmon1571ed58fe0d
diff --git a/src/quote/session.js b/src/quote/session.js
index 45aaa94..5ade5ec 100644
--- a/src/quote/session.js
+++ b/src/quote/session.js
@@ -120,5 +120,6 @@ module.exports = (client) => class QuoteSession {
/** Delete the quote session */
delete() {
this.#client.send('quote_delete_session', [this.#sessionID]);
+ delete this.#client.sessions[this.#sessionID];
}
};
diff --git a/test.js b/test.js
index b2ae70a..b449e70 100644
--- a/test.js
+++ b/test.js
@@ -1,155 +1,64 @@
+/* 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 TradingView = require('./main');
-
-const log = (...msg) => console.log('§90§30§103 TEST §0', ...msg);
-
-const client = new TradingView.Client({ DEBUG: true });
-
-client.onEvent((event, data) => {
- log('EVENT:', event, data);
-});
-
-client.onError((...error) => {
- log(...error);
-});
-
-// const quoteSession = new client.Session.Quote({
-// fields: 'price',
-// });
-
-// const BTC = new quoteSession.Market('BTCEUR');
-
-// BTC.onLoaded(() => {
-// log('BTCEUR LOADED !');
-// });
-
-// BTC.onData((data) => {
-// log('BTCEUR DATA:', data);
-// });
-
-// BTC.onError((...err) => {
-// log('BTCEUR ERROR:', err);
-// });
-
-const chart = new client.Session.Chart();
-chart.setMarket('COINBASE:BTCEUR');
-chart.setSeries('60');
-
-chart.onSymbolLoaded(() => {
- log('Market loaded:', chart.infos.full_name);
-});
-
-chart.onError((...err) => {
- log('CHART ERROR:', ...err);
-});
-
-chart.onUpdate(() => {
- const last = chart.periods[0];
- if (!last) return;
- log(`Market last period: ${last.close}`);
-});
-
-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.onReady(() => {
- log('SuperTrend ready !');
- });
-
- SuperTrend.onError((...err) => {
- log('SuperTrend ERROR:', err[0]);
- });
-
- // let QTY = 10;
- // setInterval(() => {
- // QTY += 10;
- // console.log('TRY WITH', QTY, '%');
- // indicator.setOption('default_qty_value', QTY);
-
- // SuperTrend.setIndicator(indicator);
- // }, 5000);
-
- SuperTrend.onUpdate((changes) => {
- // MarketCipher B is a strategy so it sends a strategy report
- log('SuperTrend update:', changes);
-
- const perfReport = SuperTrend.strategyReport.performance;
-
- log('Performance report:', {
- total: {
- trades: perfReport.all.totalTrades,
- perf: `${Math.round(perfReport.all.netProfitPercent * 10000) / 100} %`,
- profit: `${Math.round(perfReport.all.netProfit * 1000) / 1000} €`,
- },
- buy: {
- trades: perfReport.long.totalTrades,
- perf: `${Math.round(perfReport.long.netProfitPercent * 10000) / 100} %`,
- profit: `${Math.round(perfReport.long.netProfit * 1000) / 1000} €`,
- },
- sell: {
- trades: perfReport.short.totalTrades,
- perf: `${Math.round(perfReport.short.netProfitPercent * 10000) / 100} %`,
- profit: `${Math.round(perfReport.short.netProfit * 1000) / 1000} €`,
- },
- });
-
- if (changes.includes('fullReport')) {
- log('Last trade:', SuperTrend.strategyReport.trades[0]);
- // Do something...
-
- // // Remove SuperTrend strategy from the chart
- // SuperTrend.remove();
- }
- });
-});
-
-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.onReady(() => {
- log('MarketCipher B ready !');
- });
-
- CipherB.onError((...err) => {
- log('MarketCipher B ERROR:', err[0]);
- });
-
- CipherB.onUpdate(() => {
- const last = CipherB.periods[0];
- // MarketCipher B is not a strategy so it only sends plots values
- log('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,
- });
-
- // Do something...
+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'))) {
+ 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');
+ Object.keys(TESTS).forEach((t) => {
+ let color = '2';
+ if (TESTS[t].warnings) color = '3';
+ if (TESTS[t].errors) color = '1';
+
+ console.info(`§90§30§10${color} ${t} §0 §91E§0: ${TESTS[t].errors}§0 §93W§0: ${TESTS[t].warnings}`);
+ // console.info(` - §91 Errors:§0 ${TESTS[t].errors}`);
+ // console.info(` - §93 Warnings:§0 ${TESTS[t].warnings}`);
});
-});
-// setTimeout(() => {
-// log('Set timeframe to 240...');
-// chart.setSeries('240');
-// }, 5000);
+ process.exit(0);
+})();
-// setInterval(() => {
-// log('Fetch 100 more periods...');
-// chart.fetchMore(100);
-// }, 10000);
+setTimeout(() => {
+ console.log('§30§101 TIMEOUT §0');
+ throw new Error('Timeout');
+}, 60000);
diff --git a/tests/1. Search.js b/tests/1. Search.js
new file mode 100644
index 0000000..5843bd2
--- /dev/null
+++ b/tests/1. Search.js
@@ -0,0 +1,18 @@
+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');
+ throw new Error('Not enough results');
+ }
+
+ cb();
+};
diff --git a/tests/2. QuoteSession.js b/tests/2. QuoteSession.js
new file mode 100644
index 0000000..f749416
--- /dev/null
+++ b/tests/2. QuoteSession.js
@@ -0,0 +1,54 @@
+const TradingView = require('../main');
+
+module.exports = (log, success, warn, err, cb) => {
+ const client = new TradingView.Client();
+
+ client.onError((...error) => {
+ err('Client error', ...error);
+ throw new Error('Client 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);
+ throw new Error('Missing key');
+ }
+ });
+
+ quoteSession.delete();
+ await client.end();
+ cb();
+ });
+
+ BTC.onError((...error) => {
+ err('BTCEUR ERROR:', error);
+ throw new Error('Missing key');
+ });
+};
diff --git a/tests/3. SimpleChart.js b/tests/3. SimpleChart.js
new file mode 100644
index 0000000..7630ac5
--- /dev/null
+++ b/tests/3. SimpleChart.js
@@ -0,0 +1,61 @@
+const TradingView = require('../main');
+
+module.exports = async (log, success, warn, err, cb) => {
+ const client = new TradingView.Client();
+
+ client.onError((...error) => {
+ err('Client error', error);
+ throw new Error('Client error');
+ });
+
+ const chart = new client.Session.Chart();
+
+ chart.setMarket('BINANCE:BTCEUR', { // Set the market
+ timeframe: 'D',
+ });
+
+ chart.onError((...error) => {
+ err('Chart error', error);
+ throw new Error('Chart 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/4. Indicators.js b/tests/4. Indicators.js
new file mode 100644
index 0000000..0073f1a
--- /dev/null
+++ b/tests/4. Indicators.js
@@ -0,0 +1,99 @@
+const TradingView = require('../main');
+
+module.exports = async (log, success, warn, err, cb) => {
+ const client = new TradingView.Client();
+
+ client.onError((...error) => {
+ err('Client error', error);
+ throw new Error('Client error');
+ });
+
+ const chart = new client.Session.Chart();
+ chart.setMarket('BINANCE:BTCEUR', {
+ timeframe: '60',
+ });
+
+ chart.onError((...error) => {
+ err('Chart error', error);
+ throw new Error('Chart 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]);
+ throw new Error('SuperTrend error');
+ });
+
+ 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, '%');
+ indicator.setOption('default_qty_value', QTY);
+
+ SuperTrend.setIndicator(indicator);
+ });
+ });
+
+ 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]);
+ throw new Error('MarketCipher B error');
+ });
+
+ 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/5. BuiltInIndicator.js b/tests/5. BuiltInIndicator.js
new file mode 100644
index 0000000..4bcbc93
--- /dev/null
+++ b/tests/5. BuiltInIndicator.js
@@ -0,0 +1,41 @@
+const TradingView = require('../main');
+
+module.exports = async (log, success, warn, err, cb) => {
+ const client = new TradingView.Client();
+
+ client.onError((...error) => {
+ err('Client error', error);
+ throw new Error('Client error');
+ });
+
+ const chart = new client.Session.Chart();
+ chart.setMarket('BINANCE:BTCEUR', {
+ timeframe: '60',
+ });
+
+ chart.onError((...error) => {
+ err('Chart error', error);
+ throw new Error('Chart 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/6. FakeReplayMode.js b/tests/6. FakeReplayMode.js
new file mode 100644
index 0000000..27d7dd9
--- /dev/null
+++ b/tests/6. FakeReplayMode.js
@@ -0,0 +1,59 @@
+const TradingView = require('../main');
+
+module.exports = async (log, success, warn, err, cb) => {
+ const client = new TradingView.Client();
+
+ client.onError((...error) => {
+ err('Client error', error);
+ throw new Error('Client 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);
+ throw new Error('Chart 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) {
+ throw new Error(`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/7. ReplayMode.js b/tests/7. ReplayMode.js
new file mode 100644
index 0000000..9aa32c2
--- /dev/null
+++ b/tests/7. ReplayMode.js
@@ -0,0 +1,51 @@
+const TradingView = require('../main');
+
+module.exports = async (log, success, warn, err, cb) => {
+ const client = new TradingView.Client();
+
+ client.onError((...error) => {
+ err('Client error', error);
+ throw new Error('Client 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);
+ throw new Error('Chart 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/8. CustomChartTypes.js b/tests/8. CustomChartTypes.js
new file mode 100644
index 0000000..ec35ea3
--- /dev/null
+++ b/tests/8. CustomChartTypes.js
@@ -0,0 +1,115 @@
+const TradingView = require('../main');
+
+module.exports = async (log, success, warn, err, cb) => {
+ const client = new TradingView.Client();
+
+ client.onError((...error) => {
+ err('Client error', error);
+ throw new Error('Client error');
+ });
+
+ const chart = new client.Session.Chart();
+
+ chart.onError((...error) => {
+ err('Chart error', error);
+ throw new Error('Chart 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/9. AllErrors.js b/tests/9. AllErrors.js
new file mode 100644
index 0000000..a21e475
--- /dev/null
+++ b/tests/9. AllErrors.js
@@ -0,0 +1,146 @@
+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 () => {
+ // eslint-disable-next-line no-restricted-syntax, no-await-in-loop
+ for (const t of tests) await new Promise(t);
+ success(`Crashtests ${tests.length}/${tests.length} done !`);
+ cb();
+ })();
+};
diff --git a/tests/alerts/discordWH.js b/tests/alerts/discordWH.js
deleted file mode 100644
index cb12543..0000000
--- a/tests/alerts/discordWH.js
+++ /dev/null
@@ -1,76 +0,0 @@
-const https = require('https');
-
-/**
- * @typedef {Object} WebhookMessage Represents a Discord webhook message
- * @property {string} content
- * @property {Embed[]} [embeds]
- */
-
-/**
- * @typedef {Object} Embed Discord Embed
- * @property {string} [title]
- * @property {string} [description]
- * @property {number} [color]
- * @property {string} [url]
- * @property {string} [timestamp]
-
- * @property {Object} [author]
- * @property {string} [author.name]
- * @property {string} [author.icon_url]
- * @property {string} [author.url]
-
- * @property {Object} [thumbnail]
- * @property {string} [thumbnail.url]
-
- * @property {Object} [footer]
- * @property {string} [footer.text]
- * @property {string} [footer.icon_url]
- */
-
-/**
- * @typedef {Object} SendResult
- * @property {boolean} success
- * @property {Object} [result] If error
- * @property {string[]} [result.webhook_id]
- */
-
-/**
- * Create an instance of Discord Webhook API
- * @param {string} token Discord Webhook token (after .../api/webhooks/)
- */
-
-module.exports = function createInstance(token = '') {
- /**
- * Send a message
- * @name MessageSender
- * @param {WebhookMessage} message
- * @returns {Promise<SendResult>}
- */
- return (message) => new Promise((cb, err) => {
- const req = https.request({
- method: 'POST',
- hostname: 'discordapp.com',
- path: `/api/webhooks/${token}`,
- headers: {
- 'Content-Type': 'application/json',
- },
- maxRedirects: 20,
- }, (res) => {
- let data = '';
- res.on('data', (d) => { data += d; });
- res.on('end', () => {
- if (!data) cb({ success: true });
- else {
- cb({
- success: false,
- result: JSON.parse(data),
- });
- }
- });
- });
-
- req.on('error', err);
- req.write(JSON.stringify(message));
- req.end();
- });
-};
diff --git a/tests/alerts/drawings.js b/tests/alerts/drawings.js
deleted file mode 100644
index 7912764..0000000
--- a/tests/alerts/drawings.js
+++ /dev/null
@@ -1,41 +0,0 @@
-require('./envLoader');
-const marketAPI = require('../../main');
-
-if (!process.env.LAYOUT_ID) console.error('You need to set a layout id');
-
-const market = marketAPI(false);
-
-console.log('Connecting...');
-
-(async () => {
- /*
- * Important ! If you want to get a layout without login, you have to
- * set it in public mode. If you get an error, please wait few minutes.
- * Try getting to https://www.tradingview.com/chart/LAYOUT_ID/ in incognito mode.
- */
- const user = (process.env.SESSION_ID) ? await market.getUser(process.env.SESSION_ID) : {};
- console.log('Connected as', user.firstName || user.username || 'anonymous', '!');
-
- console.log(`Gettings drawings of '${process.env.LAYOUT_ID}' layout...`);
-
- const drawings = await market.getDrawings(process.env.LAYOUT_ID, '', {
- id: user.id,
- session: user.session,
- });
-
- const lines = drawings.filter((d) => (
- ['LineToolHorzLine', 'LineToolRay', 'LineToolTrendLine', 'LineToolHorzRay'].includes(d.type)
- && d.state.linestyle === 0
- && d.state.linewidth === 4
- ));
-
- console.log(
- `Found ${drawings.length} result(s) including ${lines.length} thick line(s):`,
- lines.map((l) => ({
- market: l.symbol,
- type: l.type,
- points: l.points,
- text: l.state.text,
- })),
- );
-})();
diff --git a/tests/alerts/envLoader.js b/tests/alerts/envLoader.js
deleted file mode 100644
index 8c4d33f..0000000
--- a/tests/alerts/envLoader.js
+++ /dev/null
@@ -1,11 +0,0 @@
-const fs = require('fs');
-
-if (fs.existsSync('.env')) {
- const envFile = fs.readFileSync('.env', 'utf8');
- envFile.split('\n') // LF
- .forEach((l) => {
- const s = l.split('=');
- // eslint-disable-next-line
- if (s[1]) process.env[s[0]] = s[1];
- });
-}
diff --git a/tests/alerts/manualAlert.js b/tests/alerts/manualAlert.js
deleted file mode 100644
index 0f8459c..0000000
--- a/tests/alerts/manualAlert.js
+++ /dev/null
@@ -1,77 +0,0 @@
-require('./envLoader');
-const { getSentNotifs, addSentNotifs } = require('./sentNotifs');
-const marketAPI = require('../../main');
-const discordWH = require('./discordWH')(process.env.DISCORD_TOKEN);
-
-if (!process.env.SYMBOLS) process.env.SYMBOLS = 'BTCEUR';
-if (!process.env.PERIOD) process.env.PERIOD = '240';
-
-const market = marketAPI(false);
-
-market.on('logged', () => {
- process.env.SYMBOLS.split(',').forEach((symbol) => {
- console.log('Listen', symbol);
-
- market.initChart({
- symbol,
- period: process.env.PERIOD,
- range: 30,
- timezone: 'Europe/Paris',
- indicators: [
- { 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',
- },
- ],
- }, (periods) => {
- if (!periods[0].CIPHER_B) return;
-
- const pBefore = periods[1];
- const p = periods[0];
-
- const gapBefore = pBefore.CIPHER_B.VWAP;
- const gap = p.CIPHER_B.VWAP;
-
- const notifID = `${symbol}@${p.$time}@BULL_TRIGGER`;
-
- if (
- p.CIPHER_B.WTWave1 <= 0 && p.CIPHER_B.WTWave1 > -35
- && gapBefore < 0 && gapBefore < gap
- && pBefore.CIPHER_B.WTWave1 < p.CIPHER_B.WTWave1
- && !getSentNotifs().includes(notifID)
- ) {
- addSentNotifs(notifID);
- console.log(symbol, 'TRIG NOW', new Date(p.$time * 1000).toLocaleString());
-
- discordWH({
- content: process.env.DISCORD_MENTION,
- embeds: [
- {
- title: `Trigger wave on ${symbol} !`,
- color: 720640,
- description: `Cipher B trigger wave detected on ${symbol}.`,
- url: `https://fr.tradingview.com/chart/?symbol=${symbol}`,
- timestamp: new Date(p.$time * 1000),
- footer: {
- text: 'TradingView',
- icon_url: 'https://tradingview.com/favicon.ico',
- },
- },
- ],
- });
- }
- });
- });
-});
diff --git a/tests/alerts/sentNotifs.js b/tests/alerts/sentNotifs.js
deleted file mode 100644
index d91c37a..0000000
--- a/tests/alerts/sentNotifs.js
+++ /dev/null
@@ -1,16 +0,0 @@
-const fs = require('fs');
-
-const sentNotifsFile = './sentNotifs.txt';
-
-exports.getSentNotifs = () => {
- if (!fs.existsSync(sentNotifsFile)) fs.writeFileSync(sentNotifsFile, '');
- return (fs.readFileSync(sentNotifsFile, 'utf8') || '').split(';').filter((n) => n);
-};
-
-exports.addSentNotifs = (notif = '') => {
- if (!fs.existsSync(sentNotifsFile)) fs.writeFileSync(sentNotifsFile, '');
- fs.writeFileSync(
- sentNotifsFile,
- `${fs.readFileSync(sentNotifsFile, 'utf8') || ''}${notif};`,
- );
-};
diff --git a/tests/alerts/strategyAlert.js b/tests/alerts/strategyAlert.js
deleted file mode 100644
index 893d9da..0000000
--- a/tests/alerts/strategyAlert.js
+++ /dev/null
@@ -1,94 +0,0 @@
-require('./envLoader');
-const { getSentNotifs, addSentNotifs } = require('./sentNotifs');
-const marketAPI = require('../../main');
-const discordWH = require('./discordWH')(process.env.DISCORD_TOKEN);
-
-const markets = [
- {
- symbol: 'EURUSD',
- period: '1D',
- settings: {
- 1: 21, // HMA 1 Length
- 3: 89, // HMA 2 Length
- 5: 7, // RSI Length
- 8: 2, // Stop Loss (%)
- 9: 1, // Take Profit (%)
- },
- },
- {
- symbol: 'GBPUSD',
- period: '1D',
- settings: {
- 1: 220, // HMA 1 Length
- 3: 150, // HMA 2 Length
- 5: 1, // RSI Length
- 8: 2, // Stop Loss (%)
- 9: 1, // Take Profit (%)
- },
- },
- {
- symbol: 'USDCAD',
- period: '1D',
- settings: {
- 1: 21, // HMA 1 Length
- 3: 89, // HMA 2 Length
- 5: 10, // RSI Length
- 8: 3, // Stop Loss (%)
- 9: 2, // Take Profit (%)
- },
- },
-];
-
-const market = marketAPI(false);
-
-market.on('logged', () => {
- markets.forEach((mrk) => {
- console.log('Listen', mrk.symbol);
-
- market.initChart({
- symbol: mrk.symbol,
- period: mrk.period || '1D',
- range: mrk.range || 30,
- timezone: mrk.timezone || 'Europe/Paris',
- indicators: [
- // My Magimix Indicator
- {
- name: 'MAGIMIX',
- id: 'USER;d90a5e852ddc439b994db6beff14d702',
- version: mrk.version || 'last',
- settings: mrk.settings || [],
- },
- ],
- }, ({ 0: p }) => {
- if (!p.MAGIMIX) return;
-
- const signalType = p.MAGIMIX.Longsignal ? 'LONG' : 'SHORT';
- const notifID = `${mrk.symbol}@MAGIMIX@${p.$time}@${signalType}`;
-
- if (
- (p.MAGIMIX.Longsignal || p.MAGIMIX.Shortsignal)
- && !getSentNotifs().includes(notifID)
- ) {
- addSentNotifs(notifID);
- console.log(mrk.symbol, 'SIGNAL', new Date(p.$time * 1000).toLocaleString());
-
- discordWH({
- content: process.env.DISCORD_MENTION,
- embeds: [
- {
- title: `Magimix ${signalType} signal for ${mrk.symbol} !`,
- color: p.MAGIMIX.Longsignal ? 3066993 : 15158332,
- description: `Magimix ${signalType} signal for ${mrk.symbol} at ${p.$prices.close} !`,
- url: `https://fr.tradingview.com/chart/?symbol=${mrk.symbol}`,
- timestamp: new Date(p.$time * 1000),
- footer: {
- text: 'TradingView',
- icon_url: 'https://tradingview.com/favicon.ico',
- },
- },
- ],
- });
- }
- });
- });
-});
diff --git a/tests/analysis.js b/tests/analysis.js
deleted file mode 100644
index 2acc4fc..0000000
--- a/tests/analysis.js
+++ /dev/null
@@ -1,13 +0,0 @@
-const marketAPI = require('../main');
-
-(async () => {
- const market = marketAPI(false);
-
- 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
deleted file mode 100644
index 9b6ac1d..0000000
--- a/tests/indicator.js
+++ /dev/null
@@ -1,42 +0,0 @@
-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/tests/prices.js b/tests/prices.js
deleted file mode 100644
index 944fd73..0000000
--- a/tests/prices.js
+++ /dev/null
@@ -1,33 +0,0 @@
-const marketAPI = require('../main');
-
-(async () => {
- const market = marketAPI();
-
- market.on('logged', async () => {
- console.log('API LOGGED');
-
- const searchBTC = (await market.search('bitcoin euro', 'crypto'))[0];
- console.log('Found Bitcoin / Euro:', searchBTC);
- market.subscribe(searchBTC.id);
-
- const btcTA = (await market.getTA(searchBTC.type, searchBTC.id));
- console.log('Technical Analysis for Bitcoin / Euro:', btcTA);
- });
-
- market.on('price', (data) => {
- console.log(data.symbol, '=>', data.price);
- });
-
- const searchETH = (await market.search('ethereum euro', 'crypto'))[0];
- console.log('Found Ethereum / Euro:', searchETH);
-
- setTimeout(() => {
- console.log('Subscribe to', searchETH.id);
- market.subscribe(searchETH.id);
- }, 10000);
-
- setTimeout(() => {
- console.log('Unsubscribe from', searchETH.id);
- market.unsubscribe(searchETH.id);
- }, 20000);
-})();
diff --git a/tests/strategy.js b/tests/strategy.js
deleted file mode 100644
index 0da86a5..0000000
--- a/tests/strategy.js
+++ /dev/null
@@ -1,56 +0,0 @@
-const marketAPI = require('../main');
-
-const market = marketAPI(false);
-
-market.on('logged', async () => {
- const indicators = (await market.searchIndicator('strategy'))
- .filter((st) => (st.type === 'strategy' && st.access !== 'invite_only'))
- .map((st) => ({
- name: st.name,
- id: st.id,
- version: st.version,
- settings: {
- commission_type: 'percent',
- commission_value: 0,
- initial_capital: 25000,
- default_qty_value: 20,
- default_qty_type: 'percent_of_equity',
- currency: 'EUR',
- pyramiding: 10,
- },
- }));
-
- let total = indicators.length;
- console.log('Found', indicators.length, 'strategies');
-
- market.initChart({
- symbol: 'COINBASE:BTCEUR',
- period: '1D',
- range: 0,
- indicators,
- }, (_, strategies) => {
- const loaded = Object.keys(strategies).length;
- console.log(`Loading... ${loaded}/${total}`);
-
- if (loaded < total) return;
- market.end();
-
- console.log(
- 'Best strategies:',
- Object.keys(strategies).map((stName) => ({
- n: stName,
- p: Math.round(strategies[stName].performance.all.netProfitPercent * 1000) / 1000,
- })).sort((a, b) => b.p - a.p),
- );
- });
-
- market.on('error', (...data) => {
- if (data[1].type === 'study_error') {
- console.error('Error with study:', indicators[data[1].data]);
- total -= 1;
- return;
- }
-
- console.error(...data);
- });
-});