Skip to content

📈 Get real-time stocks from TradingView

Init PineIndicator

Mathieu Colmonf3070ef326ff
diff --git a/examples/BuiltInIndicator.js b/examples/BuiltInIndicator.js
new file mode 100644
index 0000000..b862cd0
--- /dev/null
+++ b/examples/BuiltInIndicator.js
@@ -0,0 +1,25 @@
+const TradingView = require('../main');
+
+/*
+ This example tests built-in indicators
+ like volume-based indicators
+*/
+
+if (!process.argv[2]) throw Error('Please specify your \'sessionid\' cookie');
+
+const client = new TradingView.Client({
+ token: process.argv[2],
+});
+
+const chart = new client.Session.Chart();
+chart.setMarket('BINANCE:BTCEUR', {
+ timeframe: '60',
+});
+
+const volumeProfile = new TradingView.BuiltInIndicator('VbPSessions@tv-volumebyprice-53');
+
+const VOL = new chart.Study(volumeProfile);
+VOL.onUpdate(() => {
+ console.log((VOL.graphic.horizlines));
+ client.end();
+});
diff --git a/examples/CustomChartType.js b/examples/CustomChartType.js
index ee292b7..9385c6b 100644
--- a/examples/CustomChartType.js
+++ b/examples/CustomChartType.js
@@ -10,7 +10,7 @@ const TradingView = require('../main');
const client = new TradingView.Client({
/* Token is only required if you want to use intraday
timeframes (if you have a paid TradingView account) */
- // token: 'YOUR_SESSION_TOKEN',
+ token: process.argv[2],
});
const chart = new client.Session.Chart();
diff --git a/examples/CustomTimeframe.js b/examples/CustomTimeframe.js
new file mode 100644
index 0000000..da91436
--- /dev/null
+++ b/examples/CustomTimeframe.js
@@ -0,0 +1,29 @@
+const TradingView = require('../main');
+
+/*
+ This example tests custom
+ timeframes like 1 second
+*/
+
+if (!process.argv[2]) throw Error('Please specify your \'sessionid\' cookie');
+
+const client = new TradingView.Client({
+ token: process.argv[2],
+});
+
+const chart = new client.Session.Chart();
+chart.setTimezone('Europe/Paris');
+
+chart.setMarket('CAPITALCOM:US100', {
+ timeframe: '1S',
+ range: 10,
+});
+
+chart.onSymbolLoaded(() => {
+ console.log(chart.infos.name, 'loaded !');
+});
+
+chart.onUpdate(() => {
+ console.log('OK', chart.periods);
+ client.end();
+});
diff --git a/examples/SpecialIndicator.js b/examples/GraphicIndicator.js
similarity index 89%
rename from examples/SpecialIndicator.js
rename to examples/GraphicIndicator.js
index 334f7a0..5e0c2f6 100644
--- a/examples/SpecialIndicator.js
+++ b/examples/GraphicIndicator.js
@@ -2,8 +2,8 @@ const TradingView = require('../main');
/*
This example tests an indicator that sends
- its data in a particular way such as
- 'lines', 'labels', 'boxes' and 'tables'
+ graphic data such as 'lines', 'labels',
+ 'boxes', 'tables', 'polygons', etc...
*/
const client = new TradingView.Client();
@@ -26,7 +26,7 @@ TradingView.getIndicator('USER;8bbd8017fd3e4881bf91f4fea5e3d538').then((indic) =
});
STD.onUpdate((changes) => {
- STD.graphic;
+ // STD.graphic;
console.log('Update:', changes);
});
});
diff --git a/examples/MultipleSyncFetch.js b/examples/MultipleSyncFetch.js
new file mode 100644
index 0000000..46c56c6
--- /dev/null
+++ b/examples/MultipleSyncFetch.js
@@ -0,0 +1,38 @@
+const TradingView = require('../main');
+
+/*
+ This examples synchronously
+ fetches data from 3 indicators
+*/
+
+const client = new TradingView.Client();
+const chart = new client.Session.Chart();
+chart.setMarket('BINANCE:DOTUSDT');
+
+function getIndicData(indicator) {
+ return new Promise((res) => {
+ const STD = new chart.Study(indicator);
+
+ console.log(`Getting "${indicator.description}"...`);
+
+ STD.onUpdate(() => {
+ res(STD.periods);
+ console.log(`"${indicator.description}" done !`);
+ });
+ });
+}
+
+(async () => {
+ console.log('Getting all indicators...');
+
+ const indicData = await Promise.all([
+ await TradingView.getIndicator('PUB;3lEKXjKWycY5fFZRYYujEy8fxzRRUyF3'),
+ await TradingView.getIndicator('PUB;5nawr3gCESvSHQfOhrLPqQqT4zM23w3X'),
+ await TradingView.getIndicator('PUB;vrOJcNRPULteowIsuP6iHn3GIxBJdXwT'),
+ ].map(getIndicData));
+
+ console.log(indicData);
+ console.log('All done !');
+
+ client.end();
+})();
diff --git a/examples/Search.js b/examples/Search.js
new file mode 100644
index 0000000..4410258
--- /dev/null
+++ b/examples/Search.js
@@ -0,0 +1,15 @@
+const TradingView = require('../main');
+
+/*
+ This example tests the searching
+ functions such as 'searchMarket'
+ and 'searchIndicator'
+*/
+
+TradingView.searchMarket('BINANCE:').then((rs) => {
+ console.log('Found Markets:', rs);
+});
+
+TradingView.searchIndicator('RSI').then((rs) => {
+ console.log('Found Indicators:', rs);
+});
diff --git a/main.js b/main.js
index 5dc95a5..2f0397e 100644
--- a/main.js
+++ b/main.js
@@ -1,7 +1,9 @@
const miscRequests = require('./src/miscRequests');
const Client = require('./src/client');
+const BuiltInIndicator = require('./src/classes/BuiltInIndicator');
+const PineIndicator = require('./src/classes/PineIndicator');
-module.exports = {
- ...miscRequests,
- Client,
-};
+module.exports = { ...miscRequests };
+module.exports.Client = Client;
+module.exports.BuiltInIndicator = BuiltInIndicator;
+module.exports.PineIndicator = PineIndicator;
diff --git a/package.json b/package.json
index 7433eda..2ef8157 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@mathieuc/tradingview",
- "version": "2.0.91",
+ "version": "3.0.0",
"description": "Tradingview instant stocks API, indicator alerts, trading bot, and more !",
"main": "main.js",
"scripts": {
@@ -36,6 +36,7 @@
"@mathieuc/console": "^1.0.1",
"eslint": "^7.25.0",
"eslint-config-airbnb-base": "^14.2.1",
- "eslint-plugin-import": "^2.22.1"
+ "eslint-plugin-import": "^2.22.1",
+ "jsdoc-to-markdown": "^7.1.0"
}
}
diff --git a/src/chart/graphicParser.js b/src/chart/graphicParser.js
index df0287d..f5a7ba7 100644
--- a/src/chart/graphicParser.js
+++ b/src/chart/graphicParser.js
@@ -24,6 +24,9 @@
* @prop {GraphicLine[]} lines List of lines drawings
* @prop {GraphicBox[]} boxes List of boxes drawings
* @prop {GraphicTable[]} tables List of tables drawings
+ * @prop {GraphicHorizline[]} horizlines List of horizontal line drawings
+ * @prop {GraphicPolygon[]} polygons List of polygon drawings
+ * @prop {GraphicHist[]} hist List of hist drawings
*/
/**
@@ -50,6 +53,18 @@ module.exports = function graphicParse(rawGraphic = {}, indexes = []) {
...t,
})),
+ horizlines: Object.values(rawGraphic.horizlines ?? {}).map((h) => ({
+ ...h,
+ })),
+
+ polygons: Object.values(rawGraphic.polygons ?? {}).map((p) => ({
+ ...p,
+ })),
+
+ hist: Object.values(rawGraphic.hhists ?? {}).map((h) => ({
+ ...h,
+ })),
+
raw: rawGraphic,
};
};
diff --git a/src/chart/study.js b/src/chart/study.js
index 0950a52..8894c06 100644
--- a/src/chart/study.js
+++ b/src/chart/study.js
@@ -3,28 +3,33 @@ const { parseCompressed } = require('../protocol');
const graphicParser = require('./graphicParser');
const PineIndicator = require('../classes/PineIndicator');
+const BuiltInIndicator = require('../classes/BuiltInIndicator');
/**
* Get pine inputs
- * @param {PineIndicator} options
+ * @param {PineIndicator | BuiltInIndicator} options
*/
-function getPineInputs(options) {
- const pineInputs = { text: options.script };
+function getInputs(options) {
+ if (options instanceof PineIndicator) {
+ const pineInputs = { text: options.script };
- if (options.pineId) pineInputs.pineId = options.pineId;
- if (options.pineVersion) pineInputs.pineVersion = options.pineVersion;
+ if (options.pineId) pineInputs.pineId = options.pineId;
+ if (options.pineVersion) pineInputs.pineVersion = options.pineVersion;
- Object.keys(options.inputs).forEach((inputID) => {
- const input = options.inputs[inputID];
+ Object.keys(options.inputs).forEach((inputID) => {
+ const input = options.inputs[inputID];
- pineInputs[inputID] = {
- v: input.value,
- f: input.isFake,
- t: input.type,
- };
- });
+ pineInputs[inputID] = {
+ v: input.value,
+ f: input.isFake,
+ t: input.type,
+ };
+ });
+
+ return pineInputs;
+ }
- return pineInputs;
+ return options.options;
}
/**
@@ -187,18 +192,16 @@ module.exports = (chartSession) => class ChartStudy {
}
/**
- * @param {PineIndicator} options Indicator options
- * @param {'Script@tv-scripting-101!'
- * | 'StrategyScript@tv-scripting-101!'} [type] Indicator custom type
+ * @param {PineIndicator | BuiltInIndicator} indicator Indicator object instance
*/
- constructor(options, type = 'Script@tv-scripting-101!') {
- if (!(options instanceof PineIndicator)) {
- throw new Error(`Study options must be an instance of PineIndicator.
+ constructor(indicator) {
+ if (!(indicator instanceof PineIndicator) && !(indicator instanceof BuiltInIndicator)) {
+ throw new Error(`Indicator argument must be an instance of PineIndicator or BuiltInIndicator.
Please use 'TradingView.getIndicator(...)' function.`);
}
- /** @type {PineIndicator} Indicator options */
- this.options = options;
+ /** @type {PineIndicator | BuiltInIndicator} Indicator instance */
+ this.instance = indicator;
this.#studyListeners[this.#studID] = async (packet) => {
if (global.TW_DEBUG) console.log('§90§30§105 STUDY §0 DATA', packet);
@@ -217,7 +220,11 @@ module.exports = (chartSession) => class ChartStudy {
const period = {};
p.v.forEach((plot, i) => {
- const plotName = (i === 0 ? '$time' : this.options.plots[`plot_${i - 1}`]);
+ if (!this.instance.plots) {
+ period[i === 0 ? '$time' : `plot_${i - 1}`] = plot;
+ return;
+ }
+ const plotName = (i === 0 ? '$time' : this.instance.plots[`plot_${i - 1}`]);
if (plotName && !period[plotName]) period[plotName] = plot;
else period[`plot_${i - 1}`] = plot;
});
@@ -234,7 +241,7 @@ module.exports = (chartSession) => class ChartStudy {
if (parsed.graphicsCmds) {
if (parsed.graphicsCmds.erase) {
parsed.graphicsCmds.erase.forEach((instruction) => {
- console.log('Erase', instruction);
+ // console.log('Erase', instruction);
if (instruction.action === 'all') {
if (!instruction.type) {
Object.keys(this.#graphic).forEach((drawType) => {
@@ -332,27 +339,27 @@ module.exports = (chartSession) => class ChartStudy {
`${this.#studID}`,
'st1',
'$prices',
- type,
- getPineInputs(this.options),
+ this.instance.type,
+ getInputs(this.instance),
]);
}
/**
- * @param {PineIndicator} options Indicator options
+ * @param {PineIndicator | BuiltInIndicator} indicator Indicator instance
*/
- setIndicator(options) {
- if (!(options instanceof PineIndicator)) {
- throw new Error(`Study options must be an instance of PineIndicator.
+ setIndicator(indicator) {
+ if (!(indicator instanceof PineIndicator) && !(indicator instanceof BuiltInIndicator)) {
+ throw new Error(`Indicator argument must be an instance of PineIndicator or BuiltInIndicator.
Please use 'TradingView.getIndicator(...)' function.`);
}
- this.options = options;
+ this.instance = indicator;
chartSession.send('modify_study', [
chartSession.sessionID,
`${this.#studID}`,
'st1',
- getPineInputs(this.options),
+ getInputs(this.instance),
]);
}
diff --git a/src/classes/BuiltInIndicator.js b/src/classes/BuiltInIndicator.js
new file mode 100644
index 0000000..68bab12
--- /dev/null
+++ b/src/classes/BuiltInIndicator.js
@@ -0,0 +1,101 @@
+/**
+ * @typedef {'VbPFixed@tv-basicstudies-139!'
+ * | 'VbPFixed@tv-volumebyprice-53!'
+ * | 'VbPSessions@tv-volumebyprice-53'
+ * | 'VbPSessionsRough@tv-volumebyprice-53!'
+ * | 'VbPSessionsDetailed@tv-volumebyprice-53!'
+ * | 'VbPVisible@tv-volumebyprice-53'} BuiltInIndicatorType Built-in indicator type
+ */
+
+/**
+ * @typedef {'rowsLayout' | 'rows' | 'volume'
+ * | 'vaVolume' | 'subscribeRealtime'
+ * | 'first_bar_time' | 'first_visible_bar_time'
+ * | 'last_bar_time' | 'last_visible_bar_time'
+ * | 'extendPocRight'} BuiltInIndicatorOption Built-in indicator Option
+ */
+
+const defaultValues = {
+ 'VbPFixed@tv-basicstudies-139!': {
+ rowsLayout: 'Number Of Rows',
+ rows: 24,
+ volume: 'Up/Down',
+ vaVolume: 70,
+ subscribeRealtime: false,
+ // first_bar_time: 0000000000000,
+ // last_bar_time: 0000000000000,
+ },
+ 'VbPFixed@tv-volumebyprice-53!': {
+ rowsLayout: 'Number Of Rows',
+ rows: 24,
+ volume: 'Up/Down',
+ vaVolume: 70,
+ subscribeRealtime: false,
+ // first_bar_time: 0000000000000,
+ // last_bar_time: 0000000000000,
+ },
+ 'VbPSessions@tv-volumebyprice-53': {
+ rowsLayout: 'Number Of Rows',
+ rows: 24,
+ volume: 'Up/Down',
+ vaVolume: 70,
+ extendPocRight: false,
+ },
+ 'VbPSessionsRough@tv-volumebyprice-53!': {
+ volume: 'Up/Down',
+ vaVolume: 70,
+ },
+ 'VbPSessionsDetailed@tv-volumebyprice-53!': {
+ volume: 'Up/Down',
+ vaVolume: 70,
+ subscribeRealtime: false,
+ // first_visible_bar_time: 0000000000000,
+ // last_visible_bar_time: 0000000000000,
+ },
+ 'VbPVisible@tv-volumebyprice-53': {
+ rowsLayout: 'Number Of Rows',
+ rows: 24,
+ volume: 'Up/Down',
+ vaVolume: 70,
+ subscribeRealtime: false,
+ // first_visible_bar_time: 0000000000000,
+ // last_visible_bar_time: 0000000000000,
+ },
+};
+
+module.exports = class BuiltInIndicator {
+ /** @type {BuiltInIndicatorType} */
+ #type;
+
+ /** @return {BuiltInIndicatorType} Indicator script */
+ get type() {
+ return this.#type;
+ }
+
+ /** @type {Object<string, any>} */
+ #options = {};
+
+ /** @return {Object<string, any>} Indicator script */
+ get options() {
+ return this.#options;
+ }
+
+ /**
+ * @param {BuiltInIndicatorType} type Buit-in indocator raw type
+ */
+ constructor(type = '') {
+ if (!type) throw new Error(`Wrong buit-in indicator type "${type}".`);
+
+ this.#type = type;
+ if (defaultValues[type]) this.#options = defaultValues[type];
+ }
+
+ /**
+ * Set an option
+ * @param {BuiltInIndicatorOption} key The option you want to change
+ * @param {*} value The new value of the property
+ */
+ setOption(key, value) {
+ this.#options[key] = value;
+ }
+};
diff --git a/src/classes/PineIndicator.js b/src/classes/PineIndicator.js
index b2e6e6f..6a0cfdc 100644
--- a/src/classes/PineIndicator.js
+++ b/src/classes/PineIndicator.js
@@ -22,9 +22,16 @@
* @property {string} script Indicator script
*/
+/**
+ * @typedef {'Script@tv-scripting-101!'
+ * | 'StrategyScript@tv-scripting-101!'} IndicatorType Indicator type
+ */
module.exports = class PineIndicator {
#options;
+ /** @type {IndicatorType} */
+ #type = 'Script@tv-scripting-101!';
+
/** @param {Indicator} options Indicator */
constructor(options) {
this.#options = options;
@@ -60,6 +67,19 @@ module.exports = class PineIndicator {
return this.#options.plots;
}
+ /** @return {IndicatorType} Indicator script */
+ get type() {
+ return this.#type;
+ }
+
+ /**
+ * Set the indicator type
+ * @param {IndicatorType} type Indicator type
+ */
+ setType(type = 'Script@tv-scripting-101!') {
+ this.#type = type;
+ }
+
/** @return {string} Indicator script */
get script() {
return this.#options.script;