Coder Social home page Coder Social logo

mathieu2301 / tradingview-api Goto Github PK

View Code? Open in Web Editor NEW
1.4K 44.0 320.0 212 KB

📈 Get real-time stocks from TradingView

JavaScript 74.51% TypeScript 25.49%
tradingview tradingview-api realtime-stocks stocks stocks-api stocks-prices trading tradingview-scraper tradingview-indicator bitcoin

tradingview-api's Introduction

TradingView API GitHub stars

Tests CodeFactor GitHub latest commit Npm package yearly downloads Minimum node.js version Npm package version

Get realtime market prices and indicator values from Tradingview !

🟢 Need help with your project?

🚀 Click here for personalized assistance on your project.

🔵 Telegram group

👉 To get help, exchange tips, find collaborators, developers, missions, etc...

Join the Telegram group of the TradingView-API Community: t.me/tradingview_api

Features

  • Premium features
  • Automatically backtest many strategies and try many settings in a very little time
  • Get drawings you made on your chart
  • Works with invite-only indicators
  • Unlimited simultaneous indicators
  • Realtime
  • Get TradingView's technical analysis
  • Replay mode + Fake Replay mode (for free plan)
  • Get values from a specific date range
  • TradingView socket server emulation
  • Interract with public chats
  • Get Screener top values
  • Get Hotlists
  • Get Calendar
  • IF YOU WANT A FEATURE, ASK ME !

Possibilities

  • Trading bot
  • Discord alerts
  • Hard backtest
  • Machine Learning based indicator
  • Free replay mode for all timeframes

Installation

Stable version:

npm i @mathieuc/tradingview

Last version:

npm i github:Mathieu2301/TradingView-API

Examples

You can find all the examples and snippets in ./examples folder.

Before opening an issue

Please look at examples and previously resolved issues before opening a new one. I can't help everyone (especially for questions that are not library related but JavaScript related). Thank you for your understanding.


Problems

If you have errors in console or unwanted behavior, please create an issue here.

tradingview-api's People

Contributors

brandonros avatar clins1994 avatar code-factor avatar dependabot[bot] avatar gasparesganga avatar mathieu2301 avatar royalbrawler avatar yerofey avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tradingview-api's Issues

Stock Screener API

Loving this project so far all of the examples are working for me. I desperately need the Stock Screener results to fully automate my project, is this something you can add with a contribution ? Or if I were to add it where would I start first ?

Thanks!!

Strategy Optimization Steps

Hey Mathieu, have been playing with your library, very promising!!

I have some questions I have you can help me figure out:

  1. how to download a specific time range/timeframe of data before starting a strategy backtest
  2. how to select and get the strategy inputs
  3. how to set the ranges of inputs for which to backtest the strategy

instead of backtest inputs "2", input ranges: "2-5" with step size: "1", for example

  1. how to export the performance summary for every combination of inputs

When backtesting in the browser, changing the inputs instantly updates the performance summary.
You think this is run in the browser? Or does it actually come from the server this fast?

have you tested if this can be done multithreaded? do they throttle you?

Super excited about this! would mean i no longer have to code in EasyLanguage to optimize :)

Futures and Index's Issue

Hello, I am trying to use your socket to grab futures and index info but they send an error. The socket for just single stocks works fine but not for futures/indexes. I logged the packet coming in and the object has an error on 's'.

For simplicity I just used your example to get 'ES1!', the continuous futures price of S&P 500.

image

In that example my output is.

image

I was digging though your session code and I am stuck with it. Maybe I'm an idiot and am missing something too. Appreciate any help!

Supporting node.js version 12.19.0

I am trying to use your TradingView-API in a personal android project, and am using this library for node.js: https://github.com/janeasystems/nodejs-mobile
It seems to support no more than 12.19.0
I do not have much experience from javascript; this error is what made me think it is a version problem:

src/miscRequests.js:296
          plots[plot.id] = `${plots[plot.target] ?? plot.target}_${plot.type}`;
                                                  ^
    
    SyntaxError: Unexpected token '?'
        at wrapSafe (internal/modules/cjs/loader.js:931:16)
        at Module._compile (internal/modules/cjs/loader.js:979:27)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
        at Module.load (internal/modules/cjs/loader.js:879:32)
        at Function.Module._load (internal/modules/cjs/loader.js:724:14)
        at Module.require (internal/modules/cjs/loader.js:903:19)
        at require (internal/modules/cjs/helpers.js:74:18)
        at Object.<anonymous> (/data/data/in.tg.jhaarsi/files/JhaaRSIProjectX/main.js:1:22)
        at Module._compile (internal/modules/cjs/loader.js:1015:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)

I tested the same script on pc and termux too (node.js 14.16.0) and it seems to work fine.
Is there anything I can do to make it work on 12.19.0?

Alternatively, how can the problematic part be removed entirely (not loaded). My use is restricted to:
new TradingView.Client(), new client.Session.Chart(), chart.setMarket, TradingView.getIndicator('STD;RSI'), new chart1.Study (just RSI), study's onUpdate, study's periods.

Synchronously fetch multiple indicators

Hi Mathieu !
I'm very excited about your code.
Currently I am having problems with pro indicators such as volume profile visible range .

image

i try by my code , but it's is impossible

Screen Shot 2021-11-13 at 0 19 29

Can you help me ?

Question : Can you enable stock screener real-time ?

Hello Mathieu,

I am a programmer.
I have a pro paid account for Trading View + I am paying 2$ fee for Nasdaq Real-time ( which I get on chart ).
Yet, Stock Screener returns delay results for my Nasdaq stocks as well ( attached img )
As I built my personal TradingView bot for myself, I wonder if your APIs are presenting Real-time data for stock screener ( as most of my analysis rely on screener and not chart ) ?
TradingView-Real-Time-Data

Thank you
Etay G

Automatically reconnect after Internet connectivity changes

Sorry to be disturbing you again.
The onUpdate method is not called after internet connectivity is lost, even after it comes back on again. I know it's pretty dumb to ask and I can listen to internet connectivity changes myself and restart the client, but I want to have least footprint on battery life. Automatically reconnecting after internet connectivity is regained and optionally providing some sort of listener for it would come in handy 🐒

Error while running node .\tests\analysis.js

npm install ws OK
npm install jszip OK

PS C:\Users\XXXXXX\Source\Repos\TradingView-API> node .\tests\analysis.js
C:\Users\XXXXXX\Source\Repos\TradingView-API\miscRequests.js:312
value: settings[input.internalID] ?? settings[i] ?? input.defval,
^

SyntaxError: Unexpected token '?'
at wrapSafe (internal/modules/cjs/loader.js:1054:16)
at Module._compile (internal/modules/cjs/loader.js:1102:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Module.require (internal/modules/cjs/loader.js:1026:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object. (C:\Users\XXXXXX\Source\Repos\TradingView-API\main.js:7:5)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)

Adjusted Data

Hi Mathieu,

Can you advice where to set to get the Adjusted data?

Can I Hire You To Set This Up For Me?

Mathieu,

I would like to hire you to set this thing up for me.

I wouldn't know how and though I am slowly learning more about code I think its best if I work with someone who knows how to do it.

This is your creating so in a perfect world, I would work with you. If not, is there anyone you know that would help me?

This API is vital because I am working with invite only indicators for my strategy and I would like to back test.

I do have a premium account with live market data.

The strategies will be pretty basic and I want every ticker that I feed in to go through the same process. There are 4 indicators that I will be using.

The 2 main ones are just BUY and SELL signals... so one of the backtest, for example, will be Buy when I get a buy signal and sell when I get a sell signal... very straightforward.

I will be working mainly on the 2 hour, the 4 hour and the daily chart and I have the ability to export all the data I need with their export option... so maybe we can speed up backtest since I'll have the data locally.

There will be two parts to the project, first just a basic set up and configuration of the strategies and if I could get a brief tutorial on how to input the ticker.

The second part of the project I will want to see if we can build in a bit of automation... but for now the priority is the initial setup.

Please let me know, I am very interested in having this thing set up ASAP... I think you could do it very quickly.

I can be reached at [email protected] by phone 813-847-4199 or through here might be ok I'll install the app so I see replies and will be checking in until we talk since I see you are pretty responsive in here.

You are my first choice, let's make it happen...

Andres

Doc about how to get the ID of an indicator

I've been testing this today, and it's not as clear how to get and ID of an indicator that's not public, but published by another user and with closed source.

I see you're using WebSockets and the browser developer tools, but if you could explain it a bit more, it could help.

This is allowing me to automate some things i could not automate with other tools, so. Thanks!

Error message "Max state sessions reached"

Hi,
after some testing i get the error message "Max state sessions reached" each time since 6 hours. I already closed all browser sessions, created a new session with a new token, but it doesnt help.
Any idea?

Compile the code

Hi there,
until now I have no experience with VS Code, Electronjs or Express. I've been trying to start "TV API" for 2 weeks, but so far no way has led to the goal. So I would appreciate if someone could tell me how i get the code to run.
Many Thanks.
Magnus

MarketAPI() is not a function

I have npm and node running on a centos 7 server.
When i try to run your script it keeps giving me the following error and i'm not sure why
const market = marketAPI(); ^ TypeError: marketAPI is not a function
And this is the part of the script where MarketAPI gets called:
var mysql = require("mysql");
const marketAPI = require("@mathieuc/tradingview");

var con = mysql.createConnection({
host: "127.0.0.1",
user: "newuser",
password: "password"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});

(async () => {
const market = marketAPI();

market.on("logged", async () => {
  console.log("API LOGGED");

  const searchBTC = (await market.search("bitcoin euro", "crypto"))[0];
  market.subscribe(searchBTC.id);

Series error: seconds_not_entitled

Hi @Mathieu2301. Really appreciate you sharing this awesome TradingView project!

I currently have a Premium subscription with TradingView, which includes second-based charts. However, when I attempt to create a second-based, '1S', chart session even with a valid sessionid/token, it prompts this error: "Series error: seconds_not_entitled". The following is the code snippet:

const TradingView = require('../main');

const privateSessionId = process.env.TRADINGVIEW_SESSIONID;

const client = new TradingView.Client({
  token: privateSessionId,
});

const chart = new client.Session.Chart();
chart.setMarket('BINANCE:BTCEUR', {
  timeframe: '1S',
});

I've confirmed any other timeframe works, e.g. 1, 5, 10, W, etc.

Also, I have tried running the example, AllPrivateIndicators.js, with the same private Session ID and have confirmed that it does work.

Internal server study error with color parameter

Hi,

I run test.js with a private indicator and I got this error :
'Internal server study error: java.lang.NumberFormatException: For input string: "rgba(255,106,0,0.2)", Command info:

image

It seems it does not like that there is a color parameter but it is a problem with your code or from the server ?

Data id indicator not correct ?

Hi @Mathieu2301 !
i try to get data from basic indicator name Volume

image

When i check data-id
it's : Volume@tv-basicstudies

image

yeah, normally i use this to get the indicator id , and it works.
But when I get this ID, I get the following error:

Screen Shot 2022-02-22 at 15 37 43

i think it is a very basic indicator, so many people will get same problem with me. can you check it ?

P/s : I tried using searchIndicator function to search for this indicator id, but to my surprise, it wasn't in the search results. So, it so strange

Can't get more than 5000 candles

Hi,

I've been trying to get more than 5k one minute candles from tradingview. I noticed that with a free tradingview account you couldn't get more than 5k so I signed up for their free trial. Took out the "sessionid" cookie from the browser and inserted it to the script like below:

const client = new TradingView.Client({ token: 'code goes here' });

Tried to query one minute candles that are older than 7 days ago but it still wouldn't work.

I tried querying in the browser, i.e scroll back 7+ days on tradingview and that worked. So I don't think the issue comes from me having an account with a free trial on it.

Is there anything else that I'm doing wrong or is there anything with the library that needs to be fixed?

Here's some more of my code if that's interesting:

`
// Script
const chart = new client.Session.Chart();
chart.setMarket(symbol, {
timeframe: timeframe.toString(),
range: range, // Can be positive to get before or negative to get after
to: to - (60 * range * i),
});

let MA50 = { periods: [] };
TradingView.getIndicator('STD;EMA').then(async (indic) => {
  indic.setOption(0, 50);
  indic.setOption(1, 'close');
  indic.setOption(2, 0);
  console.log(`Loading '${indic.description}' study...`);
  MA50 = new chart.Study(indic);
});

let MA200 = { periods: [] };
TradingView.getIndicator('STD;EMA').then(async (indic) => {
  indic.setOption(0, 200);
  indic.setOption(1, 'close');
  indic.setOption(2, 0);
  console.log(`Loading '${indic.description}' study...`);
  MA200 = new chart.Study(indic);
});

await delay(5000);
console.log(chart.periods.length)
console.log(MA50.periods.length)
console.log(MA200.periods.length)

`

Thanks for the help beforehand! :)

Adding some sort of documentation

Hello, I normally don't do this kind of thing, but you seem like a nice dev and your project is very cool.

I was wondering if you, or someone else, could make some sort of documentation.

I have never used any kind of javascript so I admit that I am part of the problem, but I can't even get to run one of the 'examples' scripts.

To my understanding I have to put some sort of private-key that I get from tradingview, but I have no clue where (I haven't seen it mentioned in the examples). Anyway, the script won't even get to display an output before spitting out an error that has something to do with '../main', but that's maybe a topic for another isse.

Looking for more functions

I'm interested in pulling live data.
I was wondering if it is possible to also pull data like 24h change and trading volumes?

Internal server error on fetching private indicator - wrong color value of input

Hi,

i'm getting an error on fetching a private indicator with the following message:
image

Here are the default settings of the script, which are sent to the websocket (with an rgba value):
image

Here is the websocket message of the tradingview gui:
image

I don't know the color value. It's not rgb, hex, etc... Any idea how to fix this?

Indicator data is not correct :( Can u help pls

Here my code

const marketAPI = require('../main');
const market = marketAPI(false);
function fullreport() {
  market.initChart({
    symbol: 'BINANCE:ARPAUSDT',
    period: '1',
    range:100,
    indicators: [
      {
        id: 'PUB;9p7YCNNfzwkzhh9BTvDTJXqvV1vA0e7b',
        version: '2',
        name: 'VSH',
        author: { id: 109029, username: 'D7R' },
        image: 'B7NGM3MB',
        access: 'closed_source',
        // source: '',
        settings:[8,10,3,3,80,20,99,1,true,true,true],
        type: 'study'
      },
    ],
  }, (study) => {
    if (!study[0].VSH) return;
    console.log(study[0].VSH)
  });
}
market.on('logged', () => {
  fullreport()
});

I'm using this indicator;
aaaa

Indicator result;
aaaa

My result; :\

{
  K: 91.12527987314728,
  _plot_1: 1,
  D: 92.05727227756101,
  RSI_Overbought_: 80,
  Extended_RSI_Oversold: 1,
  RSI_Oversold: 20,
  Baseline: 50,
  K__cross_OVER_D: 1e+100,
  K_cross_UNDER_D: 91.12527987314728,
  Highlight_when_RSI_is_Overbought: 2,
  Highlight_when_RSI_is_Oversold: 1e+100,
  Highlight_when_RSI_is_Extended_Overbought: 1e+100,
  Highlight_when_RSI_is_Extended_Oversold: 1e+100   
}

My Indicator Settings;
aaaa

I want the 'K' and 'D' result in the indicator to be the same as my result
I tried diffrent time zone but not workin...

Can u help me

Maximum number of studies per chart has been reached

Hi!

I have unfortunately encountered another problem while fetching some data from tradingview.
Sometimes, mostly on higher timeframes i receive the following error in the onError handler (running within a node js docker container):
image

My sessionId is assigned to a tv premium account, normally no limits. Each process tries to fetch approx. 20 indicators for each symbol and timeframe

Anyone who has the same problem or can help here?

Feature : get watchlists

Hi Mathieu, thanks for this library it's so amazing

I was wondering if you could add the ability to get the symbols of the hotlists (volume gainers, percent change gainers) and of all the watchlists of the currently signed-in user.
I have a ton of watchlists in my account and I'd like to retrieve all of them and run a few scripts on them locally.

Thanks !

Load MY OWN private indicators?

Hi, I'd appreciate your help in this matter.

I tried this ... I'm reading the sources to figure it out with no luck .

Thanks in advance.

const marketAPI = require('@mathieuc/tradingview');
const market = marketAPI(false);



market.on('logged', () => {
  market.initChart({
    session: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    symbol: 'BTCPERP',
    period: '5',
    range: 100,
    indicators: [
      {
        name: 'My Indicator',
        id: market.searchIndicator('My Indicator').then(r => {id = r[0].id; return id}),
        version: '51.0',
        // settings: {
        //   commission_type: 'percent',
        //   commission_value: 0,
        //   initial_capital: 25000,
        //   default_qty_value: 20,
        //   default_qty_type: 'percent_of_equity',
        //   currency: 'EUR',
        //   pyramiding: 10,
        // },
      },
    ],
  }, (_, strategy) => {
    console.log(strategy);
  });

  
});

Error message "study_not_auth:Script@tv..."

Hi,
after some hours of fetching indicator values, i get the following error message in the onError event handler for each indicator:
"study_not_auth:Script@tv-scripting..."
Does anybody know how i can handle this error and start fetching again without restarting the node js process?

unknown_session_id error on create_series

Client critical error: [
  '{unknown_session_id,<<"create_series">>,<<"cs_3DJU3tGU7ovO">>,\n' +
    '                    [<<"$prices">>,<<"s1">>,<<"ser_1">>,<<"15m">>,100]}'
]

Maybe the structure has recently changed or something.

No "strategyReport.trades" data for private strategy backtest

hello, there is a question,
public strategy backtest has "strategyReport.trades" data,Indicator id: STD;Supertrend%Strategy
but private strategy backtest has no "strategyReport.trades" data, Indicator id: USER;0dab3bee3026488c9c5c139aed1f1c06

Thanks very much.

test code

const TradingView = require('..//../main');

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:ETHUSDT', {
timeframe: '240',
});

chart.onError((...error) => {
err('Chart error', error);
throw new Error('Chart error');
});

//TradingView.getIndicator('STD;Supertrend%Strategy').then((indicator) => {
TradingView.getIndicator('USER;0dab3bee3026488c9c5c139aed1f1c06').then((indicator) => {

const SuperTrend = new chart.Study(indicator);

SuperTrend.onError((...error) => {
    err('SuperTrend error', error[0]);
    throw new Error('SuperTrend error');
});

SuperTrend.onUpdate(async () => {

    const perfReport= SuperTrend.strategyReport.performance;
    
    success("trades", SuperTrend.strategyReport.trades[0])
    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} %`,
        },
    });
    SuperTrend.remove();
    chart.delete();
    await client.end();
});  

});

function success(title,data){
console.log(title, data)
}

Backtesting a Pine Strategy

Hello,
I have a customized strategy in pinescript. I need to test an like a million different parameters to determine the best combination.
I cant do that via TV. For it to be done via your API, will we need to first code it in Java?
And how much quicker it will be to test those parameters vs TV?
@Mathieu2301

Data point is missing in FakeReplayMode example output

Describe the bug
2022-04-07 is missing on the output

To Reproduce
Modify from FakeReplayMode.js example

const { Client } = require('../main');

/*
  This example tests the fake
  replay mode which works in
  intraday even with free plan
*/

console.log('----- Testing FakeReplayMode: -----');

const client = new Client({
  token: process.argv[2],
});
const chart = new client.Session.Chart();

chart.setMarket('NASDAQ:AAPL', {
  timeframe: 'D',
  range: -1, // Range is negative, so 'to' means 'from'
  to: Math.round(new Date('2022-04-05T00:00:00.000Z').getTime() / 1000),
  // to: 1600000000,
});

let interval = NaN;

chart.onUpdate(async () => {
  const times = chart.periods.map((p) => p.time);
  const closes = chart.periods.map((p) => p.close);

  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})`);
  }

  console.log('Next ->', chart.periods.length, times[0], new Date(times[0] * 1000).toISOString(), closes[0]);

  if ((times[0] + 86400) * 1000 > Date.now()) {
    await client.end();
    console.log('Done !', times.length);
  }

  chart.fetchMore(-1);
});

Output:

$ date -u --iso-8601=seconds; node FakeReplayMode.js <session token>
2022-04-09T05:26:11+00:00
----- Testing FakeReplayMode: -----
Next -> 1 1649165400 2022-04-05T13:30:00.000Z 175.06
Next -> 2 1649251800 2022-04-06T13:30:00.000Z 171.83
Next -> 4 1649424600 2022-04-08T13:30:00.000Z 170.09
Done ! 4

Environment:

  • OS: ubuntu
  • Node version: v14.17.0

Can't get labels and lines from an indicator

I'm using this indicator

    indicators: [
      { name: 'Divergence for Many v4', id: 'PUB;5xi4DbWeuIQrU0Fx6ZKiI2odDvIW9q2j', version: '10' },
    ]

and the script doesn't read anything from it

I've been debugging that a bit and first of all this is seems to be due to usage of line to produce the drawings on the screen.

I found it to sit in socket messages with dwglines / dwglabels keys on it

// Puppeteer
client.on('Network.webSocketFrameReceived', ({response}) => {
    console.log(
      response.payloadData.split(/~m~\d*~m~/)
        .filter(str => str.includes('dwglabels'))
        .map(JSON.parse)
        .map(msg => JSON.parse(msg.p[1].st4.ns.d))
        .map(d => d.graphicsCmds.create.dwglabels[0].data)
        .flat()
    )
})

Was hoping to get you a PR that would cover that corner case, however I went into rabbit hole with the indexing. Can't wrap my head around how to map it back to bars / timestamps.

Is it something you're aware of? I guess I could contribute but would need some guidance on indexing. I didn't spot anything special about that in the rest of the script.

Here is data structure from that object

Screenshot 2021-11-08 at 21 06 10

V3 getIndicator usage example

Hello Mathieu,

Can you give a usage example for the getindicator method? with settings.
i mean simply i want to see indicator results

[V3] Same output multiple times

Describe the bug

I know this was previously reported as affecting v2 in Issue #23 , but I appear to be encountering it in v3.2.0 also. If I'm doing something incorrectly, please let me know!

To Reproduce

Version Info

$ npm list
[email protected] /Users/jacraig/Documents/node/strategy_optimiser2
├── @mathieuc/[email protected]
└── @mathieuc/[email protected] (git+ssh://[email protected]/Mathieu2301/TradingView-API.git#5e769af35d4e3de1281044a620de354650bb94a2)

./IndicatorTest.js

/* eslint-disable no-await-in-loop */
/* eslint-disable import/no-dynamic-require */
/* eslint-disable no-restricted-syntax */
/* eslint-disable global-require */

const fs = require('fs');
require('@mathieuc/console')(
  '§', // Character you want to use (defaut: '§')
  true, // Active timestamp (defaut: false)
);

const TESTS = {};

function err(name) {
  return (...msg) => {
    TESTS[name].errors += 1;
    console.error('§30§101 > §0', ...msg);
  };
}

function warn(name) {
  return (...msg) => {
    TESTS[name].warnings += 1;
    console.warn('§30§103 > §0', ...msg);
  };
}

function log() {
  return (...msg) => console.log('§30§107 > §0', ...msg);
}

function success() {
  return (...msg) => console.info('§30§102 > §0', ...msg);
}

(async () => {
  console.info('§90§30§104 ==== Starting tests ==== §0');

  for (const file of fs.readdirSync('./tests').filter((f) => f.endsWith('.js'))) {
    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}`);
  });

  process.exit(0);
})();

setTimeout(() => {
  console.log('§30§101 TIMEOUT §0');
  throw new Error('Timeout');
}, 60000);

./tests/4. Indicators.js

const TradingView = require('@mathieuc/tradingview');

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);
    });
  });

};

Output:

$ node IndicatorTest.js
[06/03 16:16:09]  ==== Starting tests ====
[06/03 16:16:09]  4. Indicators
[06/03 16:16:10]  >  Performances: {
  total: { trades: 229, perf: '-2.73 %' },
  buy: { trades: 115, perf: '5.95 %' },
  sell: { trades: 114, perf: '-8.67 %' }
}
[06/03 16:16:10]  >  TRY WITH 20 %
[06/03 16:16:10]  >  Performances: {
  total: { trades: 229, perf: '-2.73 %' },
  buy: { trades: 115, perf: '5.95 %' },
  sell: { trades: 114, perf: '-8.67 %' }
}
[06/03 16:16:10]  >  TRY WITH 30 %
[06/03 16:16:11]  >  Performances: {
  total: { trades: 229, perf: '-4.92 %' },
  buy: { trades: 115, perf: '8.35 %' },
  sell: { trades: 114, perf: '-13.27 %' }
}
[06/03 16:16:11]  >  TRY WITH 40 %
[06/03 16:16:11]  >  Performances: {
  total: { trades: 229, perf: '-4.92 %' },
  buy: { trades: 115, perf: '8.35 %' },
  sell: { trades: 114, perf: '-13.27 %' }
}
[06/03 16:16:11]  >  TRY WITH 50 %
[06/03 16:16:11]  >  Performances: {
  total: { trades: 229, perf: '-10.76 %' },
  buy: { trades: 115, perf: '12.08 %' },
  sell: { trades: 114, perf: '-22.84 %' }
}
[06/03 16:16:11]  ==== ALL TESTS DONE ====

[06/03 16:16:11]  4. Indicators  E: 0 W: 0

Expected behavior

$ node IndicatorTest.js
[06/03 16:16:58]  ==== Starting tests ====
[06/03 16:16:58]  4. Indicators
[06/03 16:16:02]  >  Performances: {
  total: { trades: 229, perf: '-2.73 %' },
  buy: { trades: 115, perf: '5.95 %' },
  sell: { trades: 114, perf: '-8.67 %' }
}
[06/03 16:16:02]  >  TRY WITH 20 %
[06/03 16:16:02]  >  Performances: {
  total: { trades: 229, perf: '-2.73 %' },
  buy: { trades: 115, perf: '5.95 %' },
  sell: { trades: 114, perf: '-8.67 %' }
}
[06/03 16:16:02]  >  TRY WITH 30 %
[06/03 16:16:03]  >  Performances: {
  total: { trades: 229, perf: '-4.92 %' },
  buy: { trades: 115, perf: '8.35 %' },
  sell: { trades: 114, perf: '-13.27 %' }
}
[06/03 16:16:03]  >  TRY WITH 40 %
[06/03 16:16:04]  >  Performances: {
  total: { trades: 229, perf: '-7.62 %' },
  buy: { trades: 115, perf: '10.39 %' },
  sell: { trades: 114, perf: '-18.01 %' }
}
[06/03 16:16:04]  >  TRY WITH 50 %
[06/03 16:16:04]  >  Performances: {
  total: { trades: 229, perf: '-10.76 %' },
  buy: { trades: 115, perf: '12.08 %' },
  sell: { trades: 114, perf: '-22.84 %' }
}
[06/03 16:16:04]  ==== ALL TESTS DONE ====

[06/03 16:16:04]  4. Indicators  E: 0 W: 0

Environment:

  • OS: macOS Monterey v12.2.1
  • Node version: v8.5.1

Do I need a premium plan to retrieve data?

I was wondering if I need an account with a paid plan to retrieve data using your API. I haven't found that they restrict any data to premium, only some UI functions.

Renko chart's indicator value does not match GUI-based TradingView's, given same configurations

Both the code and the GUI-based TradingView chart have the exact same configurations - chart type, timeframe, regular session, box size, etc. Both also have the exact same indicator, CM_Ultimate_MA_MTF_V2. The issue is that the study.periods[0].MultiTimeframe_Moving_Avg indicator value output should be the same as the GUI-based TradingView chart, but unfortunately they are not the same.

const TradingView = require('../main');

const privateSessionId = process.env.TRADINGVIEW_SESSIONID;

const client = new TradingView.Client({
  token: privateSessionId,
});

const chart = new client.Session.Chart();
chart.setMarket('NASDAQ:AAPL', {
  session: 'regular',
  type: 'Renko',
  timeframe: '1',
  inputs: {
    source: 'close',
    sources: 'Close',
    boxSize: 3,
    style: 'Traditional',
    atrLength: 14,
    wicks: true,
  },
});

const publicFmp = TradingView.searchIndicator('CM_Ultimate_MA_MTF_V2').then(async (indicator) => {
  indicator[0].source = '-',
  console.log(
    '*** Indicator information \n',
    indicator[0],
  );
  const pineIndicator = await indicator[0].get();
  const study = new chart.Study(pineIndicator);
  study.onUpdate(() => {
    console.log(
      `\n*** Chart time and close:\n`,
      chart.periods[0].time,
      chart.periods[0].close
    );
    console.log(
      '\n*** Indicator value:\n',
      study.periods[0].MultiTimeframe_Moving_Avg,
    );
  })
})

TradingView-API Output

image

GUI-based TradingView Chart

image

Some indicators do not return any data

I used private indicator, but it returned undefined data, here is my script:

const marketAPI = require('@mathieuc/tradingview');

(async () => {
  const market = marketAPI();

  market.on('logged', () => {
    market.initChart({
      session: 'xxx',
      symbol: 'BINANCE:DOTUSDT',
      period: '15',
      range: 100,
      indicators: [
        { name: 'PerfectEntry', id: 'PUB;jxt0ms0lQ94CocR78tJeedfprTMBhKeq', version: '1.0' },
        { name: 'ConfirmationEntry', id: 'PUB;V5kM00yH2hQS6vpCNph64r9WWZUgBKAT', version: '1.0' },
        { name: 'CIPHER_B', id: 'PUB;uA35GeckoTA2EfgI63SD2WCSmca4njxp', version: '15.0' },
        { name: 'CCMA', id: 'PUB;5nawr3gCESvSHQfOhrLPqQqT4zM23w3X', version: '6.0' },
      ],
    }, (periods, strategy) => {
      if (!periods[0].CIPHER_B) return;
      if (!periods[0].CCMA) return;
      if (!periods[0].PerfectEntry) return;
      // if (!periods[0].ConfirmationEntry) return;
  
      console.log({
        price: periods[0].$prices.close,
        moneyFlow: (periods[0].CIPHER_B.RSIMFIArea >= 0) ? 'POSITIVE' : 'NEGATIVE',
        MA: (periods[0].CCMA.Plot <= periods[0].$prices.close) ? 'ABOVE' : 'UNDER',
        PE: periods[0].PerfectEntry,
        CE: periods[0].ConfirmationEntry
      })
    });
  });
})();

Result:

{
  price: 44.53,
  moneyFlow: 'NEGATIVE',
  MA: 'ABOVE',
  PE: {
    High_Target: 44.80592209906545,
    Low_Target: 44.00025475379346,
    Bar_Color: 1,
    Buy_Alert: 0,
    Sell_Alert: 0,
    Sell_Signal: 0,
    Buy_Signal: 0,
    Default_RSI_Signal_Background_Color: 1e+100,
    Higher_High: 0,
    Lower_Low: 0
  },
  CE: undefined
}

Where can I find the chart_id for getDrawings?

Hi,

I am trying to load my drawings from trading view, but it the api requires a chart_id, which is in my case not 1, as the default value for the call, but something like this: qtNCHx5Z6fbT. Tried to look up in the debugger where this value come from, but I had no luck. And there's no example for this unfortunately in the examples folder.

So is it still possible with this api to load my custom drawings from the tv?
Thanks!

[V2] Same output multiple times

Implementation

import marketAPI from '@mathieuc/tradingview'

const market = marketAPI(false); // 'false' for chart-only mode

market.on('logged', () => {
  market.initChart({
    symbol: 'BINANCE:BTCGBP',
    period: '1D',
    indicators: [
      // Get EMA
      // https://pine-facade.tradingview.com/pine-facade/translate/STD;EMA/last/
      { name: 'ema200', id: 'STD;EMA', version: 'last', settings: [200, 'close']},

      // get RSI
      { name: 'rsi14', id: 'STD;RSI', version: 'last', settings: [14]},
    ],
  }, (periods) => {
    if (!periods[0].rsi14) return;
    if (!periods[0].ema200) return;

    console.log(periods[0])
  });
});

Output

{
  '$time': 1637366400,
  '$prices': {
    open: 43457.02,
    close: 44552.23,
    max: 44572,
    min: 42867.52,
    change: 84.11
  },
  ema200: { EMA: 35630.68940158015 },
  rsi14: { RSI: 47.6888273113946 },
}
{
  '$time': 1637366400,
  '$prices': {
    open: 43457.02,
    close: 44552.23,
    max: 44572,
    min: 42867.52,
    change: 84.11
  },
  ema200: { EMA: 35630.68940158015 },
  rsi14: { RSI: 47.6888273113946 },
}
{
  '$time': 1637366400,
  '$prices': {
    open: 43457.02,
    close: 44552.23,
    max: 44572,
    min: 42867.52,
    change: 84.11
  },
  ema200: { EMA: 35630.68940158015 },
  rsi14: { RSI: 47.6888273113946 },
}
{
  '$time': 1637366400,
  '$prices': {
    open: 43457.02,
    close: 44552.23,
    max: 44572,
    min: 42867.52,
    change: 84.11
  },
  ema200: { EMA: 35630.68940158015 },
  rsi14: { RSI: 47.6888273113946 },
}

Error: Unexpected token '??'

./node_modules/@mathieuc/tradingview/miscRequests.js 306:43
Module parse failed: Unexpected token (306:43)
File was processed with these loaders:

  • ./node_modules/babel-loader/lib/index.js
    You may need an additional loader to handle the result of these loaders.
    | name: input.name,
    | type: input.type,
    value: settings[input.internalID] ?? settings[i] ?? input.defval,

| defVal: input.defval,
| hidden: !!input.isHidden,

thank in advance

Alerts feature

Hey first of all thank you very much for this awesome library. I was wondering if you could add the ability to add alerts at specific prices on different symbols and then get notified when they reach that price.

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.