📈 Get real-time stocks from TradingView
TypeScript backtestingbacktesting-trading-strategiesbitcoinchartscryptocryptocurrencyethereumrealtime-stocksstocksstocks-apistocks-pricestradingtradingviewtradingview-apitradingview-indicatortradingview-replaytradingview-scraper
Add charts and studies
Mathieu Colmon17f817d9225e
diff --git a/package.json b/package.jsonindex 19c386b..7433eda 100644--- a/package.json+++ b/package.json@@ -33,6 +33,7 @@},"devDependencies": {"@babel/eslint-parser": "^7.15.7",+ "@mathieuc/console": "^1.0.1","eslint": "^7.25.0","eslint-config-airbnb-base": "^14.2.1","eslint-plugin-import": "^2.22.1"diff --git a/src/chart/session.js b/src/chart/session.jsnew file mode 100644index 0000000..ed55189--- /dev/null+++ b/src/chart/session.js@@ -0,0 +1,288 @@+const { genSessionID } = require('../utils');++const studyConstructor = require('./study');++/** @typedef {Object<string, Function[]>} StudyListeners */++/**+ * @typedef {Object} ChartSessionBridge+ * @prop {string} sessionID+ * @prop {StudyListeners} studyListeners+ * @prop {import('../client').SendPacket} send+*/++/**+ * @typedef {'seriesLoaded' | 'symbolLoaded' | 'update' | 'error'} ChartEvent+ */++/**+ * @typedef {Object} PricePeriod+ * @prop {number} time Period timestamp+ * @prop {number} open Period open value+ * @prop {number} close Period close value+ * @prop {number} max Period max value+ * @prop {number} min Period min value+ * @prop {number} change Period change absolute value+ */++/**+ * @typedef {Object} Subsession+ * @prop {string} id Subsession ID (ex: 'regular')+ * @prop {string} description Subsession description (ex: 'Regular')+ * @prop {string} privat If private+ * @prop {string} session Session (ex: '24x7')+ * @prop {string} session-display Session display (ex: '24x7')+ *+ * @typedef {Object} MarketInfos+ * @prop {string} series_id Used series (ex: 'sds_sym_1')+ * @prop {string} base_currency Base currency (ex: 'BTC')+ * @prop {string} base_currency_id Base currency ID (ex: 'XTVCBTC')+ * @prop {string} name Market short name (ex: 'BTCEUR')+ * @prop {string} full_name Market full name (ex: 'COINBASE:BTCEUR')+ * @prop {string} pro_name Market pro name (ex: 'COINBASE:BTCEUR')+ * @prop {string} description Market symbol description (ex: 'BTC/EUR')+ * @prop {string} short_description Market symbol short description (ex: 'BTC/EUR')+ * @prop {string} exchange Market exchange (ex: 'COINBASE')+ * @prop {string} listed_exchange Market exchange (ex: 'COINBASE')+ * @prop {string} provider_id Values provider ID (ex: 'coinbase')+ * @prop {string} currency_id Used currency ID (ex: 'EUR')+ * @prop {string} currency_code Used currency code (ex: 'EUR')+ * @prop {string} variable_tick_size Variable tick size+ * @prop {number} pricescale Price scale+ * @prop {number} pointvalue Point value+ * @prop {string} session Session (ex: '24x7')+ * @prop {string} session_display Session display (ex: '24x7')+ * @prop {string} type Market type (ex: 'crypto')+ * @prop {boolean} has_intraday If intraday values are available+ * @prop {boolean} fractional If market is fractional+ * @prop {boolean} is_tradable If the market is curently tradable+ * @prop {number} minmov Minimum move value+ * @prop {number} minmove2 Minimum move value 2+ * @prop {string} timezone Used timezone+ * @prop {boolean} is_replayable If the replay mode is available+ * @prop {boolean} has_adjustment If the adjustment mode is enabled ????+ * @prop {boolean} has_extended_hours Has extended hours+ * @prop {string} bar_source Bar source+ * @prop {string} bar_transform Bar transform+ * @prop {boolean} bar_fillgaps Bar fill gaps+ * @prop {string} allowed_adjustment Allowed adjustment (ex: 'none')+ * @prop {string} subsession_id Subsession ID (ex: 'regular')+ * @prop {string} pro_perm Pro permission (ex: '')+ * @prop {[]} base_name Base name (ex: ['COINBASE:BTCEUR'])+ * @prop {[]} legs Legs (ex: ['COINBASE:BTCEUR'])+ * @prop {Subsession[]} subsessions Sub sessions+ * @prop {[]} typespecs Typespecs (ex: [])+ * @prop {[]} resolutions Resolutions (ex: [])+ * @prop {[]} aliases Aliases (ex: [])+ * @prop {[]} alternatives Alternatives (ex: [])+ */++/**+ * @param {import('../client').ClientBridge} client+ */+module.exports = (client) => class ChartSession {+ #sessionID = genSessionID('cs');++ /** Parent client */+ #client = client;++ /** @type {StudyListeners} */+ #studyListeners = {};++ /**+ * Table of periods values indexed by timestamp+ * @type {Object<number, PricePeriod[]>}+ */+ #periods = {};++ /** @return {PricePeriod[]} List of periods values */+ get periods() {+ return Object.values(this.#periods).sort((a, b) => b.time - a.time);+ }++ #callbacks = {+ seriesLoaded: [],+ symbolLoaded: [],+ update: [],++ event: [],+ error: [],+ };++ /**+ * @param {ChartEvent} ev Client event+ * @param {...{}} data Packet data+ */+ #handleEvent(ev, ...data) {+ this.#callbacks[ev].forEach((e) => e(...data));+ this.#callbacks.event.forEach((e) => e(ev, ...data));+ }++ #handleError(...msgs) {+ if (this.#callbacks.error.length === 0) console.error(...msgs);+ else this.#handleEvent('error', ...msgs);+ }++ constructor() {+ this.#client.sessions[this.#sessionID] = {+ type: 'chart',+ onData: (packet) => {+ console.log('§90§30§106 CHART SESSION §0 DATA', packet);++ if (typeof packet.data[1] === 'string' && this.#studyListeners[packet.data[1]]) {+ this.#studyListeners[packet.data[1]](packet);+ return;+ }++ if (packet.type === 'symbol_resolved') {+ this.#handleEvent('symbolLoaded', {+ series_id: packet.data[1],+ ...packet.data[2],+ });+ return;+ }++ if (['timescale_update', 'du'].includes(packet.type)) {+ Object.keys(packet.data[1]).forEach((k) => {+ if (k === '$prices') {+ const periods = packet.data[1].$prices;+ if (!periods || !periods.s) return;++ periods.s.forEach((p) => {+ this.#periods[p.v[0]] = {+ time: p.v[0],+ open: p.v[1],+ close: p.v[4],+ max: p.v[2],+ min: p.v[3],+ change: Math.round(p.v[5] * 100) / 100,+ };+ });++ return;+ }++ if (this.#studyListeners[k]) this.#studyListeners[k](packet);+ });++ this.#handleEvent('update');+ return;+ }++ if (packet.type === 'symbol_error') {+ this.#handleError(`(${packet.data[1]}) Symbol error:`, packet.data[2]);+ return;+ }++ if (packet.type === 'series_error') {+ this.#handleError('Series error:', packet.data);+ return;+ }++ if (packet.type === 'critical_error') {+ const [, name, description] = packet.data;+ this.#handleError('Critical error:', name, description);+ }+ },+ };++ this.#client.send('chart_create_session', [this.#sessionID]);+ }++ #series = []++ /**+ * @param {import('../types').TimeFrame} timeframe Chart period timeframe+ * @param {number} [range] Number of loaded periods/candles (Default: 100)+ * @param {string} [ID] Series ID (Default: 'sds_sym_1')+ */+ setSeries(timeframe = '240', range = 100, ID = 'sds_sym_1') {+ this.#periods = {};+ this.#client.send(`${this.#series.includes(ID) ? 'modify' : 'create'}_series`, [+ this.#sessionID,+ '$prices',+ 's1',+ ID,+ timeframe,+ !this.#series.includes(ID) ? range : '',+ ]);++ if (!this.#series.includes(ID)) this.#series.push(ID);+ }++ /**+ * Set the chart market+ * @param {string} symbol Market symbol+ * @param {Object} [options] Market options+ * @param {'splits' | 'dividends'} [options.adjustment] Market adjustment+ * @param {string} [options.series] Series ID (Default: 'sds_sym_1')+ */+ setMarket(symbol, options = {}) {+ this.#periods = {};++ this.#client.send('resolve_symbol', [+ this.#sessionID,+ options.series || 'sds_sym_1',+ `={"symbol":"${symbol || 'BTCEUR'}","adjustment":"${options.adjustment || 'splits'}","session":"regular"}`,+ ]);+ }++ /**+ * Set the chart timezone+ * @param {import('../types').Timezone} timezone New timezone+ */+ setTimezone(timezone) {+ this.#periods = {};+ this.#client.send('switch_timezone', [this.#sessionID, timezone]);+ }++ /**+ * Fetch x additional previous periods/candles values+ * @param {number} number Number of additional periods/candles you want to fetch+ */+ fetchMore(number = 1) {+ this.#client.send('request_more_data', [this.#sessionID, '$prices', number]);+ }++ /**+ * When a symbol is loaded+ * @param {(marketInfos: MarketInfos) => void} cb+ * @event+ */+ onSymbolLoaded(cb) {+ this.#callbacks.symbolLoaded.push(cb);+ }++ /**+ * When a chart update happens+ * @param {() => void} cb+ * @event+ */+ onUpdate(cb) {+ this.#callbacks.update.push(cb);+ }++ /**+ * When chart error happens+ * @param {(...any) => void} cb Callback+ * @event+ */+ onError(cb) {+ this.#callbacks.error.push(cb);+ }++ /** @type {ChartSessionBridge} */+ #chartSession = {+ sessionID: this.#sessionID,+ studyListeners: this.#studyListeners,+ send: (t, p) => this.#client.send(t, p),+ };++ Study = studyConstructor(this.#chartSession);++ /** Delete the chart session */+ delete() {+ this.#client.send('quote_delete_session', [this.#sessionID]);+ delete this.#client.sessions[this.#sessionID];+ }+};diff --git a/src/chart/study.js b/src/chart/study.jsnew file mode 100644index 0000000..510d7bd--- /dev/null+++ b/src/chart/study.js@@ -0,0 +1,327 @@+const { genSessionID } = require('../utils');+const { parseCompressed } = require('../protocol');++const PineIndicator = require('../classes/PineIndicator');++/**+ * Get pine inputs+ * @param {PineIndicator} options+ */+function getPineInputs(options) {+ const pineInputs = { text: options.script };++ 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];++ pineInputs[inputID] = {+ v: input.value,+ f: input.isFake,+ t: input.type,+ };+ });++ return pineInputs;+}++/**+ * @typedef {Object} TradeReport Trade report++ * @property {Object} entry Trade entry+ * @property {string} entry.name Trade name+ * @property {'long' | 'short'} entry.type Entry type (long/short)+ * @property {number} entry.value Entry price value+ * @property {number} entry.time Entry timestamp++ * @property {Object} exit Trade exit+ * @property {'' | string} exit.name Trade name ('' if false exit)+ * @property {number} exit.value Exit price value+ * @property {number} exit.time Exit timestamp++ * @property {number} quantity Trade quantity+ * @property {RelAbsValue} profit Trade profit+ * @property {RelAbsValue} cumulative Trade cummulative profit+ * @property {RelAbsValue} runup Trade run-up+ * @property {RelAbsValue} drawdown Trade drawdown+ */++/**+ * @typedef {Object} PerfReport+ * @property {number} avgBarsInTrade Average bars in trade+ * @property {number} avgBarsInWinTrade Average bars in winning trade+ * @property {number} avgBarsInLossTrade Average bars in losing trade+ * @property {number} avgTrade Average trade gain+ * @property {number} avgTradePercent Average trade performace+ * @property {number} avgLosTrade Average losing trade gain+ * @property {number} avgLosTradePercent Average losing trade performace+ * @property {number} avgWinTrade Average winning trade gain+ * @property {number} avgWinTradePercent Average winning trade performace+ * @property {number} commissionPaid Commission paid+ * @property {number} grossLoss Gross loss value+ * @property {number} grossLossPercent Gross loss percent+ * @property {number} grossProfit Gross profit+ * @property {number} grossProfitPercent Gross profit percent+ * @property {number} largestLosTrade Largest losing trade gain+ * @property {number} largestLosTradePercent Largent losing trade performance (percentage)+ * @property {number} largestWinTrade Largest winning trade gain+ * @property {number} largestWinTradePercent Largest winning trade performance (percentage)+ * @property {number} marginCalls Margin calls+ * @property {number} maxContractsHeld Max Contracts Held+ * @property {number} netProfit Net profit+ * @property {number} netProfitPercent Net performance (percentage)+ * @property {number} numberOfLosingTrades Number of losing trades+ * @property {number} numberOfWiningTrades Number of winning trades+ * @property {number} percentProfitable Strategy winrate+ * @property {number} profitFactor Profit factor+ * @property {number} ratioAvgWinAvgLoss Ratio Average Win / Average Loss+ * @property {number} totalOpenTrades Total open trades+ * @property {number} totalTrades Total trades+*/++/**+ * @typedef {Object} StrategyReport+ * @property {'EUR' | 'USD' | 'JPY' | '' | 'CHF'} [currency] Selected currency+ * @property {TradeReport[]} trades Trade list starting by the last+ * @property {Object} history History Chart value+ * @property {number[]} [history.buyHold] Buy hold values+ * @property {number[]} [history.buyHoldPercent] Buy hold percent values+ * @property {number[]} [history.drawDown] Drawdown values+ * @property {number[]} [history.drawDownPercent] Drawdown percent values+ * @property {number[]} [history.equity] Equity values+ * @property {number[]} [history.equityPercent] Equity percent values+ * @property {Object} performance Strategy performance+ * @property {PerfReport} [performance.all] Strategy long/short performances+ * @property {PerfReport} [performance.long] Strategy long performances+ * @property {PerfReport} [performance.short] Strategy short performances+ * @property {number} [performance.buyHoldReturn] Strategy Buy & Hold Return+ * @property {number} [performance.buyHoldReturnPercent] Strategy Buy & Hold Return percent+ * @property {number} [performance.maxDrawDown] Strategy max drawdown+ * @property {number} [performance.maxDrawDownPercent] Strategy max drawdown percent+ * @property {number} [performance.openPL] Strategy Open P&L (Profit And Loss)+ * @property {number} [performance.openPLPercent] Strategy Open P&L (Profit And Loss) percent+ * @property {number} [performance.sharpeRatio] Strategy Sharpe Ratio+ * @property {number} [performance.sortinoRatio] Strategy Sortino Ratio+ */++/**+ * @param {import('./session').ChartSessionBridge} chartSession+ */+module.exports = (chartSession) => class ChartStudy {+ #studID = genSessionID('st');++ #studyListeners = chartSession.studyListeners;++ /**+ * Table of periods values indexed by timestamp+ * @type {Object<number, {}[]>}+ */+ #periods = {};++ /** @return {{}[]} List of periods values */+ get periods() {+ return Object.values(this.#periods).sort((a, b) => b.time - a.time);+ }++ /** @type {StrategyReport} */+ #strategyReport = {+ trades: [],+ history: {},+ performance: {},+ };++ /** @return {StrategyReport} Get the strategy report if available */+ get strategyReport() {+ return this.#strategyReport;+ }++ #callbacks = {+ studyCompleted: [],+ update: [],++ event: [],+ error: [],+ };++ /**+ * @param {ChartEvent} ev Client event+ * @param {...{}} data Packet data+ */+ #handleEvent(ev, ...data) {+ this.#callbacks[ev].forEach((e) => e(...data));+ this.#callbacks.event.forEach((e) => e(ev, ...data));+ }++ #handleError(...msgs) {+ if (this.#callbacks.error.length === 0) console.error(...msgs);+ else this.#handleEvent('error', ...msgs);+ }++ /**+ * @param {PineIndicator} options Indicator options+ * @param {'Script@tv-scripting-101!'+ * | 'StrategyScript@tv-scripting-101!'} [type] Indicator custom type+ */+ constructor(options, type = 'Script@tv-scripting-101!') {+ if (!(options instanceof PineIndicator)) {+ throw new Error(`Study options must be an instance of PineIndicator.+ Please use 'TradingView.getIndicator(...)' function.`);+ }++ /** @type {PineIndicator} Indicator options */+ this.options = options;++ this.#studyListeners[this.#studID] = async (packet) => {+ console.log('§90§30§105 STUDY §0 DATA', packet);++ if (packet.type === 'study_completed') {+ this.#handleEvent('studyCompleted');+ return;+ }++ if (['timescale_update', 'du'].includes(packet.type)) {+ const changes = [];+ const data = packet.data[1][this.#studID];++ if (data && data.st && data.st[0]) {+ data.st.forEach((p) => {+ const period = {};++ p.v.forEach((plot, i) => {+ const plotName = (i === 0 ? '$time' : this.options.plots[`plot_${i - 1}`]);+ if (!period[plotName]) period[plotName] = plot;+ else period[`plot_${i - 1}`] = plot;+ });++ this.#periods[p.v[0]] = period;+ });++ changes.push('plots');+ }++ if (data.ns && data.ns.d) {+ const parsed = JSON.parse(data.ns.d);++ if (parsed.data && parsed.data.report && parsed.data.report.performance) {+ this.#strategyReport.performance = parsed.data.report.performance;+ changes.push('perfReport');+ }++ if (parsed.dataCompressed) {+ const parsedC = await parseCompressed(parsed.dataCompressed);++ this.#strategyReport = {+ currency: parsedC.report.currency,++ trades: parsedC.report.trades.reverse().map((t) => ({+ entry: {+ name: t.e.c,+ type: (t.e.tp[0] === 's' ? 'short' : 'long'),+ value: t.e.p,+ time: t.e.tm,+ },+ exit: {+ name: t.x.c,+ value: t.x.p,+ time: t.x.tm,+ },+ quantity: t.q,+ profit: t.tp,+ cumulative: t.cp,+ runup: t.rn,+ drawdown: t.dd,+ })),++ history: {+ buyHold: parsedC.report.buyHold,+ buyHoldPercent: parsedC.report.buyHoldPercent,+ drawDown: parsedC.report.drawDown,+ drawDownPercent: parsedC.report.drawDownPercent,+ equity: parsedC.report.equity,+ equityPercent: parsedC.report.equityPercent,+ },++ performance: parsedC.report.performance,+ };++ changes.push('fullReport');+ }+ }++ this.#handleEvent('update', changes);+ return;+ }++ if (packet.type === 'study_error') {+ this.#handleError(packet.data[3], packet.data[4]);+ }+ };++ chartSession.send('create_study', [+ chartSession.sessionID,+ `${this.#studID}`,+ 'st1',+ '$prices',+ type,+ getPineInputs(this.options),+ ]);+ }++ /**+ * @param {PineIndicator} options Indicator options+ */+ setIndicator(options) {+ if (!(options instanceof PineIndicator)) {+ throw new Error(`Study options must be an instance of PineIndicator.+ Please use 'TradingView.getIndicator(...)' function.`);+ }++ this.options = options;++ chartSession.send('modify_study', [+ chartSession.sessionID,+ `${this.#studID}`,+ 'st1',+ getPineInputs(this.options),+ ]);+ }++ /**+ * When the indicator is ready+ * @param {() => void} cb+ * @event+ */+ onReady(cb) {+ this.#callbacks.studyCompleted.push(cb);+ }++ /** @typedef {'plots' | 'perfReport' | 'fullReport'} UpdateChangeType */++ /**+ * When an indicator update happens+ * @param {(changes: UpdateChangeType[]) => void} cb+ * @event+ */+ onUpdate(cb) {+ this.#callbacks.update.push(cb);+ }++ /**+ * When indicator error happens+ * @param {(...any) => void} cb Callback+ * @event+ */+ onError(cb) {+ this.#callbacks.error.push(cb);+ }++ /** Remove the study */+ remove() {+ chartSession.send('remove_study', [+ chartSession.sessionID,+ this.#studID,+ ]);+ delete this.#studyListeners[this.#studID];+ }+};diff --git a/src/classes/PineIndicator.js b/src/classes/PineIndicator.jsnew file mode 100644index 0000000..b2e6e6f--- /dev/null+++ b/src/classes/PineIndicator.js@@ -0,0 +1,112 @@+/**+ * @typedef {Object} IndicatorInput+ * @property {string} name Input name+ * @property {string} inline Input inline name+ * @property {string} [internalID] Input internal ID+ * @property {string} [tooltip] Input tooltip+ * @property {'text' | 'source' | 'integer' | 'float' | 'resolution' | 'bool'} type Input type+ * @property {string | number | boolean} value Input default value+ * @property {boolean} isHidden If the input is hidden+ * @property {boolean} isFake If the input is fake+ * @property {string[]} [options] Input options if the input is a select+ */++/**+ * @typedef {Object} Indicator+ * @property {string} pineId Indicator ID+ * @property {string} pineVersion Indicator version+ * @property {string} description Indicator description+ * @property {string} shortDescription Indicator short description+ * @property {Object<string, IndicatorInput>} inputs Indicator inputs+ * @property {Object<string, string>} plots Indicator plots+ * @property {string} script Indicator script+ */++module.exports = class PineIndicator {+ #options;++ /** @param {Indicator} options Indicator */+ constructor(options) {+ this.#options = options;+ }++ /** @return {string} Indicator ID */+ get pineId() {+ return this.#options.pineId;+ }++ /** @return {string} Indicator version */+ get pineVersion() {+ return this.#options.pineVersion;+ }++ /** @return {string} Indicator description */+ get description() {+ return this.#options.description;+ }++ /** @return {string} Indicator short description */+ get shortDescription() {+ return this.#options.shortDescription;+ }++ /** @return {Object<string, IndicatorInput>} Indicator inputs */+ get inputs() {+ return this.#options.inputs;+ }++ /** @return {Object<string, string>} Indicator plots */+ get plots() {+ return this.#options.plots;+ }++ /** @return {string} Indicator script */+ get script() {+ return this.#options.script;+ }++ /**+ * Set an option+ * @param {number | string} key The key can be ID of the property (`in_{ID}`),+ * the inline name or the internalID.+ * @param {*} value The new value of the property+ */+ setOption(key, value) {+ let propI = '';++ if (this.#options.inputs[`in_${key}`]) propI = `in_${key}`;+ else if (this.#options.inputs[key]) propI = key;+ else {+ propI = Object.keys(this.#options.inputs).find((I) => (+ this.#options.inputs[I].inline === key+ || this.#options.inputs[I].internalID === key+ ));+ }++ if (propI && this.#options.inputs[propI]) {+ const input = this.#options.inputs[propI];++ const types = {+ bool: 'Boolean',+ integer: 'Number',+ float: 'Number',+ text: 'String',+ };++ if (+ (input.type === 'bool' && typeof value !== 'boolean')+ || (input.type === 'integer' && typeof value !== 'number')+ || (input.type === 'float' && typeof value !== 'number')+ || (input.type === 'text' && typeof value !== 'string')+ ) {+ throw new Error(`Input '${input.name}' (${propI}) must be a ${types[input.type]} !`);+ }++ if (input.options && !input.options.includes(value)) {+ throw new Error(`Input '${input.name}' (${propI}) must be one of these values:`, input.options);+ }++ input.value = value;+ } else throw new Error(`Input '${key}' not found (${propI}).`);+ }+};diff --git a/src/client.js b/src/client.jsindex d204888..d75e8aa 100644--- a/src/client.js+++ b/src/client.js@@ -1,9 +1,10 @@const WebSocket = require('ws');const misc = require('./miscRequests');+const protocol = require('./protocol');const quoteSessionGenerator = require('./quote/session');-const chartSessionGenerator = require('./quote/session');+const chartSessionGenerator = require('./chart/session');/*** @typedef {Object} Session@@ -152,60 +153,48 @@ module.exports = class Client {#parsePacket(str) {if (!this.isOpen) return;- str.replace(/~h~/g, '').split(/~m~[0-9]{1,}~m~/g)- .map((p) => {- if (!p) return false;- try {- return JSON.parse(p);- } catch (error) {- console.warn('Cant parse', p);- return false;- }- })- .filter((p) => p)- .forEach((packet) => {- console.log('[CLIENT] PACKET', packet);- if (typeof packet === 'number') { // Ping- const pingStr = `~h~${packet}`;- this.#ws.send(`~m~${pingStr.length}~m~${pingStr}`);- this.#handleEvent('ping', packet);+ protocol.parseWSPacket(str).forEach((packet) => {+ console.log('§90§30§107 CLIENT §0 PACKET', packet);+ if (typeof packet === 'number') { // Ping+ this.#ws.send(protocol.formatWSPacket(`~h~${packet}`));+ this.#handleEvent('ping', packet);+ return;+ }++ if (packet.m === 'protocol_error') { // Error+ this.#handleError('Client critical error:', packet.p);+ this.#ws.close();+ return;+ }++ if (packet.m && packet.p) { // Normal packet+ const parsed = {+ type: packet.m,+ data: packet.p,+ };++ const session = packet.p[0];++ if (session && this.#sessions[session]) {+ this.#sessions[session].onData(parsed);return;}+ }- if (packet.m === 'protocol_error') { // Error- this.#handleError('Client critical error:', packet.p);- this.#ws.close();- return;- }-- if (packet.m && packet.p) { // Normal packet- const parsed = {- type: packet.m,- session: packet.p[0],- data: packet.p[1],- };-- if (parsed.session && this.#sessions[parsed.session]) {- this.#sessions[parsed.session].onData(parsed);- return;- }- }-- if (!this.#logged) {- this.#handleEvent('logged', packet);- return;- }+ if (!this.#logged) {+ this.#handleEvent('logged', packet);+ return;+ }- this.#handleEvent('data', packet);- });+ this.#handleEvent('data', packet);+ });}#sendQueue = [];/** @type {SendPacket} Send a custom packet */send(t, p = []) {- const msg = JSON.stringify({ m: t, p });- this.#sendQueue.push(`~m~${msg.length}~m~${msg}`);+ this.#sendQueue.push(protocol.formatWSPacket({ m: t, p }));this.sendQueue();}diff --git a/src/miscRequests.js b/src/miscRequests.jsindex e3cc6be..ffb596b 100644--- a/src/miscRequests.js+++ b/src/miscRequests.js@@ -1,5 +1,7 @@const https = require('https');+const PineIndicator = require('./classes/PineIndicator');+const indicators = ['Recommend.Other', 'Recommend.All', 'Recommend.MA'];const indicList = [];@@ -132,7 +134,7 @@ module.exports = {},/**- * @typedef {Object} SearchResult+ * @typedef {Object} SearchMarketResult* @property {string} id* @property {string} exchange* @property {string} fullExchange@@ -147,9 +149,9 @@ module.exports = {* Find a symbol* @param {string} search Keywords* @param {'stock' | 'futures' | 'forex' | 'cfd' | 'crypto' | 'index' | 'economic'} [filter]- * @returns {Promise<SearchResult[]>} Search results+ * @returns {Promise<SearchMarketResult[]>} Search results*/- async search(search, filter = '') {+ async searchMarket(search, filter = '') {const data = await request({host: 'symbol-search.tradingview.com',path: `/symbol_search/?text=${search.replace(/ /g, '%20')}&type=${filter}`,@@ -179,7 +181,7 @@ module.exports = {},/**- * @typedef {Object} IndicatorResult+ * @typedef {Object} SearchIndicatorResult* @property {string} id Script ID* @property {string} version Script version* @property {string} name Script complete name@@ -188,12 +190,13 @@ module.exports = {* @property {string | ''} source Script source (if available)* @property {'study' | 'strategy'} type Script type (study / strategy)* @property {'open_source' | 'closed_source' | 'invite_only' | 'other'} access Script access type+ * @property {() => Promise<Indicator>} get Get the full indicator informations*//*** Find an indicator* @param {string} search Keywords- * @returns {Promise<IndicatorResult[]>} Search results+ * @returns {Promise<SearchIndicatorResult[]>} Search results*/async searchIndicator(search = '') {if (!indicList.length) {@@ -230,6 +233,9 @@ module.exports = {access: 'closed_source',source: '',type: (ind.extra && ind.extra.kind) ? ind.extra.kind : 'study',+ get() {+ return module.exports.getIndicator(ind.scriptIdPart, ind.version);+ },})),...data.results.map((ind) => ({@@ -244,42 +250,20 @@ module.exports = {access: ['open_source', 'closed_source', 'invite_only'][ind.access - 1] || 'other',source: ind.scriptSource,type: (ind.extra && ind.extra.kind) ? ind.extra.kind : 'study',+ get() {+ return module.exports.getIndicator(ind.scriptIdPart, ind.version);+ },})),];},- /**- * @typedef {Object} indicatorInput- * @property {string} name- * @property {string} inline Inline name- * @property { 'text' | 'source' | 'integer' | 'float' | 'resolution' | 'bool' } type- * @property {string | number | boolean} value- * @property {string | number | boolean} defVal- * @property {boolean} hidden- * @property {boolean} isFake- * @property {string[]} [options]- */-- /**- * @typedef {Object} Indicator- * @property {string} pineId Indicator ID- * @property {string} pineVersion Indicator version- * @property {string} description Indicator description- * @property {string} shortDescription Indicator short description- * @property {string} typeID Indicator script type ID- * @property {Object<string, indicatorInput>} inputs Indicator inputs- * @property {Object<string, string>} plots Indicator plots- * @property {string} script Indicator script- */-/*** Get an indicator* @param {string} id Indicator ID (Like: PUB;XXXXXXXXXXXXXXXXXXXXX)* @param {'last' | string} [version] Wanted version of the indicator- * @param {'study' | 'strategy'} [type] Script type- * @returns {Promise<Indicator>} Indicator+ * @returns {Promise<PineIndicator>} Indicator*/- async getIndicator(id, version = 'last', settings = [], type = 'study') {+ async getIndicator(id, version = 'last') {const indicID = id.replace(/ |%/g, '%25');let data = await request({@@ -294,7 +278,6 @@ module.exports = {}if (!data.success || !data.result.metaInfo || !data.result.metaInfo.inputs) {- console.error(data);throw new Error('Inexistent or unsupported indicator');}@@ -302,18 +285,17 @@ module.exports = {data.result.metaInfo.inputs.forEach((input) => {if (['text', 'pineId', 'pineVersion'].includes(input.id)) return;- const inline = input.inline || input.name.replace(/ /g, '_').replace(/[^a-zA-Z0-9_]/g, '');-- const i = parseInt(input.id.replace(/[^0-9]/g, ''), 10);inputs[input.id] = {name: input.name,+ inline: input.inline || input.name.replace(/ /g, '_').replace(/[^a-zA-Z0-9_]/g, ''),+ internalID: input.internalID,+ tooltip: input.tooltip,+type: input.type,- value: settings[input.internalID] ?? settings[i] ?? input.defval,- defVal: input.defval,- hidden: !!input.isHidden,+ value: input.defval,+ isHidden: !!input.isHidden,isFake: !!input.isFake,- inline,};if (input.options) inputs[input.id].options = input.options;@@ -325,19 +307,15 @@ module.exports = {plots[plotId] = data.result.metaInfo.styles[plotId].title.replace(/ /g, '_').replace(/[^a-zA-Z0-9_]/g, '');});- return {+ return new PineIndicator({pineId: indicID,pineVersion: version,description: data.result.metaInfo.description,shortDescription: data.result.metaInfo.shortDescription,- typeID: {- study: 'Script@tv-scripting-101!',- strategy: 'StrategyScript@tv-scripting-101!',- }[type] || type,inputs,plots,script: data.result.ilTemplate,- };+ });},/**diff --git a/src/protocol.js b/src/protocol.jsnew file mode 100644index 0000000..a57d469--- /dev/null+++ b/src/protocol.js@@ -0,0 +1,54 @@+const JSZip = require('jszip');++/**+ * @typedef {Object} TWPacket+ * @prop {string} [m] Packet type+ * @prop {[session: string, {}]} [p] Packet data+ */++module.exports = {+ /**+ * Parse websocket packet+ * @param {string} str Websocket raw data+ * @returns {TWPacket[]} TradingView packets+ */+ parseWSPacket(str) {+ return str.replace(/~h~/g, '').split(/~m~[0-9]{1,}~m~/g)+ .map((p) => {+ if (!p) return false;+ try {+ return JSON.parse(p);+ } catch (error) {+ console.warn('Cant parse', p);+ return false;+ }+ })+ .filter((p) => p);+ },++ /**+ * Format websocket packet+ * @param {TWPacket} packet TradingView packet+ * @returns {string} Websocket raw data+ */+ formatWSPacket(packet) {+ const msg = typeof packet === 'object'+ ? JSON.stringify(packet)+ : packet;+ return `~m~${msg.length}~m~${msg}`;+ },++ /**+ * Parse compressed data+ * @param {string} data Compressed data+ * @returns {Promise<{}>} Parsed data+ */+ async parseCompressed(data) {+ const zip = new JSZip();+ return JSON.parse(+ await (+ await zip.loadAsync(data, { base64: true })+ ).file('').async('text'),+ );+ },+};diff --git a/src/quote/market.js b/src/quote/market.jsindex ff781e9..eb1d552 100644--- a/src/quote/market.js+++ b/src/quote/market.js@@ -1,17 +1,19 @@/**- * @typedef { 'loaded' | 'data' | 'error' } MarketEvent+ * @typedef {'loaded' | 'data' | 'error'} MarketEvent*//*** @param {import('./session').QuoteSessionBridge} quoteSession*/module.exports = (quoteSession) => class QuoteMarket {- #symbolList = quoteSession.symbols;+ #symbolListeners = quoteSession.symbolListeners;#symbol;#symbolListenerID = 0;+ #lastData = {};+#callbacks = {loaded: [],data: [],@@ -20,8 +22,6 @@ module.exports = (quoteSession) => class QuoteMarket {error: [],};- #lastData = {};-/*** @param {MarketEvent} ev Client event* @param {...{}} data Packet data@@ -42,36 +42,35 @@ module.exports = (quoteSession) => class QuoteMarket {constructor(symbol) {this.#symbol = symbol;- if (!this.#symbolList[symbol]) {- this.#symbolList[symbol] = [];+ if (!this.#symbolListeners[symbol]) {+ this.#symbolListeners[symbol] = [];quoteSession.send('quote_add_symbols', [quoteSession.sessionID,symbol,]);}- this.#symbolListenerID = this.#symbolList[symbol].length;+ this.#symbolListenerID = this.#symbolListeners[symbol].length;- this.#symbolList[symbol][this.#symbolListenerID] = (packet) => {- console.log('[MARKET] DATA', packet);+ this.#symbolListeners[symbol][this.#symbolListenerID] = (packet) => {+ console.log('§90§30§105 MARKET §0 DATA', packet);- if (packet.type === 'qsd' && packet.data.s === 'ok') {+ if (packet.type === 'qsd' && packet.data[1].s === 'ok') {this.#lastData = {...this.#lastData,- ...packet.data.v,+ ...packet.data[1].v,};this.#handleEvent('data', this.#lastData);return;}- if (packet.type === 'qsd' && packet.data.s === 'error') {- this.#handleError('Market error', packet.data);- return;- }-if (packet.type === 'quote_completed') {this.#handleEvent('loaded');return;}++ if (packet.type === 'qsd' && packet.data[1].s === 'error') {+ this.#handleError('Market error', packet.data);+ }};}@@ -113,12 +112,12 @@ module.exports = (quoteSession) => class QuoteMarket {/** Close this listener */close() {- if (this.#symbolList[this.#symbol].length <= 1) {+ if (this.#symbolListeners[this.#symbol].length <= 1) {quoteSession.send('quote_remove_symbols', [quoteSession.sessionID,this.#symbol,]);}- delete this.#symbolList[this.#symbol][this.#symbolListenerID];+ delete this.#symbolListeners[this.#symbol][this.#symbolListenerID];}};diff --git a/src/quote/session.js b/src/quote/session.jsindex b176ca6..1cc647e 100644--- a/src/quote/session.js+++ b/src/quote/session.js@@ -2,12 +2,12 @@ const { genSessionID } = require('../utils');const quoteMarketConstructor = require('./market');-/** @typedef {Object<string, Function[]>} SymbolList */+/** @typedef {Object<string, Function[]>} SymbolListeners *//*** @typedef {Object} QuoteSessionBridge* @prop {string} sessionID- * @prop {SymbolList} symbols+ * @prop {SymbolListeners} symbolListeners* @prop {import('../client').SendPacket} send*/@@ -51,38 +51,49 @@ function getQuoteFields(fieldsType) {];}-/**- * @typedef {Object} quoteSessionOptions Quote Session options- * @prop {'all' | 'price'} [fields] Asked quote fields- * @prop {quoteField[]} [customFields] List of asked quote fields- */-/*** @param {import('../client').ClientBridge} client*/module.exports = (client) => class QuoteSession {#sessionID = genSessionID('qs');+ /** Parent client */#client = client;- /** @type {SymbolList} */- #symbols = {};+ /** @type {SymbolListeners} */+ #symbolListeners = {};++ /**+ * @typedef {Object} quoteSessionOptions Quote Session options+ * @prop {'all' | 'price'} [fields] Asked quote fields+ * @prop {quoteField[]} [customFields] List of asked quote fields+ *//*** @param {quoteSessionOptions} options Quote settings options*/- constructor(options) {+ constructor(options = {}) {this.#client.sessions[this.#sessionID] = {type: 'quote',onData: (packet) => {- console.log('[QUOTE SESSION] DATA', packet);-- if (packet.type === 'quote_completed' && this.#symbols[packet.data]) {- this.#symbols[packet.data].forEach((h) => h(packet));+ console.log('§90§30§102 QUOTE SESSION §0 DATA', packet);++ if (packet.type === 'quote_completed') {+ const symbol = packet.data[1];+ if (!this.#symbolListeners[symbol]) {+ this.#client.send('quote_remove_symbols', [this.#sessionID, symbol]);+ return;+ }+ this.#symbolListeners[symbol].forEach((h) => h(packet));}- if (packet.type === 'qsd' && this.#symbols[packet.data.n]) {- this.#symbols[packet.data.n].forEach((h) => h(packet));+ if (packet.type === 'qsd') {+ const symbol = packet.data[1].n;+ if (!this.#symbolListeners[symbol]) {+ this.#client.send('quote_remove_symbols', [this.#sessionID, symbol]);+ return;+ }+ this.#symbolListeners[symbol].forEach((h) => h(packet));}},};@@ -99,7 +110,7 @@ module.exports = (client) => class QuoteSession {/** @type {QuoteSessionBridge} */#quoteSession = {sessionID: this.#sessionID,- symbols: this.#symbols,+ symbolListeners: this.#symbolListeners,send: (t, p) => this.#client.send(t, p),};@@ -108,8 +119,6 @@ module.exports = (client) => class QuoteSession {/** Delete the quote session */delete() {- this.#quoteSession.send('quote_delete_session', [- this.#quoteSession.sessionID,- ]);+ this.#client.send('quote_delete_session', [this.#sessionID]);}};diff --git a/src/types.js b/src/types.jsindex 5ddba77..cb63c95 100644--- a/src/types.js+++ b/src/types.js@@ -1,5 +1,32 @@/*** @typedef {string} MarketSymbol Market symbol (like: 'BTCEUR' or 'KRAKEN:BTCEUR')+ *+ * @typedef {'Etc/UTC' | 'exchange'+ * | 'Pacific/Honolulu' | 'America/Juneau' | 'America/Los_Angeles'+ * | 'America/Phoenix' | 'America/Vancouver' | 'US/Mountain'+ * | 'America/El_Salvador' | 'America/Bogota' | 'America/Chicago'+ * | 'America/Lima' | 'America/Mexico_City' | 'America/Caracas'+ * | 'America/New_York' | 'America/Toronto' | 'America/Argentina/Buenos_Aires'+ * | 'America/Santiago' | 'America/Sao_Paulo' | 'Atlantic/Reykjavik'+ * | 'Europe/Dublin' | 'Africa/Lagos' | 'Europe/Lisbon' | 'Europe/London'+ * | 'Europe/Amsterdam' | 'Europe/Belgrade' | 'Europe/Berlin'+ * | 'Europe/Brussels' | 'Europe/Copenhagen' | 'Africa/Johannesburg'+ * | 'Africa/Cairo' | 'Europe/Luxembourg' | 'Europe/Madrid' | 'Europe/Malta'+ * | 'Europe/Oslo' | 'Europe/Paris' | 'Europe/Rome' | 'Europe/Stockholm'+ * | 'Europe/Warsaw' | 'Europe/Zurich' | 'Europe/Athens' | 'Asia/Bahrain'+ * | 'Europe/Helsinki' | 'Europe/Istanbul' | 'Asia/Jerusalem' | 'Asia/Kuwait'+ * | 'Europe/Moscow' | 'Asia/Qatar' | 'Europe/Riga' | 'Asia/Riyadh'+ * | 'Europe/Tallinn' | 'Europe/Vilnius' | 'Asia/Tehran' | 'Asia/Dubai'+ * | 'Asia/Muscat' | 'Asia/Ashkhabad' | 'Asia/Kolkata' | 'Asia/Almaty'+ * | 'Asia/Bangkok' | 'Asia/Jakarta' | 'Asia/Ho_Chi_Minh' | 'Asia/Chongqing'+ * | 'Asia/Hong_Kong' | 'Australia/Perth' | 'Asia/Shanghai' | 'Asia/Singapore'+ * | 'Asia/Taipei' | 'Asia/Seoul' | 'Asia/Tokyo' | 'Australia/Brisbane'+ * | 'Australia/Adelaide' | 'Australia/Sydney' | 'Pacific/Norfolk'+ * | 'Pacific/Auckland' | 'Pacific/Fakaofo' | 'Pacific/Chatham'} Timezone (Chart) timezone+ *+ * @typedef {'1' | '3' | '5' | '15' | '30'+ * | '45' | '60' | '120' | '180' | '240'+ * | '1D' | '1W' | '1M'} TimeFrame*/module.exports = {};diff --git a/test.js b/test.jsindex e983806..73e44c8 100644--- a/test.js+++ b/test.js@@ -1,34 +1,154 @@+require('@mathieuc/console')(+ '§', // Character you want to use (defaut: '§')+ true, // Active timestamp (defaut: false)+);+const TradingView = require('./main');-const client = new TradingView.Client({- token: null,-});+const log = (...msg) => console.log('§90§30§103 TEST §0', ...msg);++const client = new TradingView.Client();client.onEvent((event, data) => {- console.log('[TEST] EVENT:', event, data);+ log('EVENT:', event, data);});-const quoteSession = new client.Session.Quote({- fields: 'price',+client.onError((...error) => {+ log(...error);});-// const quoteSession2 = new client.Session.Quote({+// const quoteSession = new client.Session.Quote({// fields: 'price',// });-const BTC = new quoteSession.Market('BTCEUR');-BTC.onData((data) => {- console.log('[TEST] BTCEUR DATA', data);+// 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((market) => {+ log('Market loaded:', market.full_name);});-BTC.onError((...err) => {- console.log('[TEST] BTCEUR ERROR', err);++chart.onError((...err) => {+ log('CHART ERROR:', ...err);});-// const BTC = new quoteSession.Symbol('BTCEUR');-// BTC.onData((symbol) => {-// console.log(symbol);-// });+chart.onUpdate(() => {+ const last = chart.periods[0];+ 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 stratefgy 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...+ });+});// setTimeout(() => {-// BTC.close();+// log('Set timeframe to 240...');+// chart.setSeries('240');// }, 5000);++// setInterval(() => {+// log('Fetch 100 more periods...');+// chart.fetchMore(100);+// }, 10000);