Giter VIP home page Giter VIP logo

tvdatafeed's Introduction

TvDatafeed

A simple TradingView historical Data Downloader. Tvdatafeed allows downloading upto 5000 bars on any of the supported timeframe.

If you found the content useful and want to support my work, you can buy me a coffee!

Installation

This module is installed via pip:

pip install tvdatafeed

or installing from github repo

pip install --upgrade --no-cache-dir git+https://github.com/StreamAlpha/tvdatafeed.git

For usage instructions, watch these videos-

v1.2 tutorial with installation and backtrader usage

Watch the video

Full tutorial

Watch the video


About release 2.0.0

Version 2.0.0 is a major release and is not backward compatible. make sure you update your code accordingly. Thanks to stefanomorni for contributing and removing selenium dependancy.

Usage

Import the packages and initialize with your tradingview username and password.

from tvDatafeed import TvDatafeed, Interval

username = 'YourTradingViewUsername'
password = 'YourTradingViewPassword'

tv = TvDatafeed(username, password)

You may use without logging in, but in some cases tradingview may limit the symbols and some symbols might not be available.

To use it without logging in

tv = TvDatafeed()

when using without login, following warning will be shown you are using nologin method, data you access may be limited


Getting Data

To download the data use tv.get_hist method.

It accepts following arguments and returns pandas dataframe

(symbol: str, exchange: str = 'NSE', interval: Interval = Interval.in_daily, n_bars: int = 10, fut_contract: int | None = None, extended_session: bool = False) -> DataFrame)

for example-

# index
nifty_index_data = tv.get_hist(symbol='NIFTY',exchange='NSE',interval=Interval.in_1_hour,n_bars=1000)

# futures continuous contract
nifty_futures_data = tv.get_hist(symbol='NIFTY',exchange='NSE',interval=Interval.in_1_hour,n_bars=1000,fut_contract=1)

# crudeoil
crudeoil_data = tv.get_hist(symbol='CRUDEOIL',exchange='MCX',interval=Interval.in_1_hour,n_bars=5000,fut_contract=1)

# downloading data for extended market hours
extended_price_data = tv.get_hist(symbol="EICHERMOT",exchange="NSE",interval=Interval.in_1_hour,n_bars=500, extended_session=False)

Search Symbol

To find the exact symbols for an instrument you can use tv.search_symbol method.

You need to provide search text and optional exchange. This will return a list of macthing instruments and their symbol.

tv.search_symbol('CRUDE','MCX')

Calculating Indicators

Indicators data is not downloaded from tradingview. For that you can use TA-Lib. Check out this video for installation and usage instructions-

Watch the video


Supported Time Intervals

Following timeframes intervals are supported-

Interval.in_1_minute

Interval.in_3_minute

Interval.in_5_minute

Interval.in_15_minute

Interval.in_30_minute

Interval.in_45_minute

Interval.in_1_hour

Interval.in_2_hour

Interval.in_3_hour

Interval.in_4_hour

Interval.in_daily

Interval.in_weekly

Interval.in_monthly


Read this before creating an issue

Before creating an issue in this library, please follow the following steps.

  1. Search the problem you are facing is already asked by someone else. There might be some issues already there, either solved/unsolved related to your problem. Go to issues page, use is:issue as filter and search your problem. image

  2. If you feel your problem is not asked by anyone or no issues are related to your problem, then create a new issue.

  3. Describe your problem in detail while creating the issue. If you don't have time to detail/describe the problem you are facing, assume that I also won't be having time to respond to your problem.

  4. Post a sample code of the problem you are facing. If I copy paste the code directly from issue, I should be able to reproduce the problem you are facing.

  5. Before posting the sample code, test your sample code yourself once. Only sample code should be tested, no other addition should be there while you are testing.

  6. Have some print() function calls to display the values of some variables related to your problem.

  7. Post the results of print() functions also in the issue.

  8. Use the insert code feature of github to inset code and print outputs, so that the code is displyed neat. !

  9. If you have multiple lines of code, use tripple grave accent ( ``` ) to insert multiple lines of code.

    Example:

    1659809630082

tvdatafeed's People

Contributors

anshulthakur avatar oak06 avatar stefanomorni avatar streamalpha 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

tvdatafeed's Issues

Unable to fetch data in other time frames

fetch_data = tv.get_hist(symbol.format(symbol), 'BINANCE', Interval.in_5_minute, 5000)returns:
Connection is already closed.
File "build\bdist.win-amd64\egg\tvfeed\main.py", line 173, in get_hist
File "build\bdist.win-amd64\egg\tvfeed\main.py", line 89, in __create_df
AttributeError: 'NoneType' object has no attribute 'group'

However if the same code is run with:
fetch_data = tv.get_hist(symbol.format(symbol), 'BINANCE', Interval.in_1_minute, 5000)returns no errors whatsoever.

I am using the no login method currently.
since chrome drivers have changed.

Chrome driver version autoinstall

There's currently a problem with this library. It installs an outdated chromedriver by default. I would be much preferred to install a chromedriver compatible with the currently installed chrome browser.

Here's my workaround and dirty patch.

My code;

from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
tv=TvDatafeed(auto_login=False, chromedriver=driver)

And the patch to the library. The constructor is:

def __init__(
        self,
        username=None,
        password=None,
        chromedriver_path=None,
        chromedriver=None,
        auto_login=True,
    ) -> None:
....
        self.chromedriver = chromedriver

Then we change def __webdriver_init(self): around line 270 like this:

            if self.chromedriver is not None:
                driver = self.chromedriver
            else:
                driver = webdriver.Chrome(
                    self.chromedriver_path, desired_capabilities=caps, options=options
                )

Sorry for the extremely dirty patch. I hope the idea is clear.

You are using nologin method, data you access may be limited

Hello,

While scalping data from TV, getting the following error.

python3 data_gather.py --name=ITC
Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="overlap-manager-root"]/div/span/div[1]/div/div/div[1]/div[2]/div"}
  (Session info: headless chrome=96.0.4664.93)
Stacktrace:
0   chromedriver                        0x0000000108554de9 __gxx_personality_v0 + 587625
1   chromedriver                        0x00000001084df433 __gxx_personality_v0 + 105907
2   chromedriver                        0x000000010809a578 chromedriver + 173432
3   chromedriver                        0x00000001080d00e2 chromedriver + 393442
4   chromedriver                        0x00000001080d02a1 chromedriver + 393889
5   chromedriver                        0x0000000108102904 chromedriver + 600324
6   chromedriver                        0x00000001080ed92d chromedriver + 514349
7   chromedriver                        0x0000000108100583 chromedriver + 591235
8   chromedriver                        0x00000001080edb53 chromedriver + 514899
9   chromedriver                        0x00000001080c320e chromedriver + 340494
10  chromedriver                        0x00000001080c4485 chromedriver + 345221
11  chromedriver                        0x00000001085106db __gxx_personality_v0 + 307291
12  chromedriver                        0x00000001085275cf __gxx_personality_v0 + 401231
13  chromedriver                        0x000000010852d7ab __gxx_personality_v0 + 426283
14  chromedriver                        0x000000010852893a __gxx_personality_v0 + 406202
15  chromedriver                        0x0000000108504d81 __gxx_personality_v0 + 259841
16  chromedriver                        0x0000000108544c78 __gxx_personality_v0 + 521720
17  chromedriver                        0x0000000108544e01 __gxx_personality_v0 + 522113
18  chromedriver                        0x000000010855c268 __gxx_personality_v0 + 617448
19  libsystem_pthread.dylib             0x00007fff74375661 _pthread_body + 340
20  libsystem_pthread.dylib             0x00007fff7437550d _pthread_body + 0
21  libsystem_pthread.dylib             0x00007fff74374bf9 thread_start + 13
, ('no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="overlap-manager-root"]/div/span/div[1]/div/div/div[1]/div[2]/div"}\n  (Session info: headless chrome=96.0.4664.93)', None, ['0   chromedriver                        0x0000000108554de9 __gxx_personality_v0 + 587625', '1   chromedriver                        0x00000001084df433 __gxx_personality_v0 + 105907', '2   chromedriver                        0x000000010809a578 chromedriver + 173432', '3   chromedriver                        0x00000001080d00e2 chromedriver + 393442', '4   chromedriver                        0x00000001080d02a1 chromedriver + 393889', '5   chromedriver                        0x0000000108102904 chromedriver + 600324', '6   chromedriver                        0x00000001080ed92d chromedriver + 514349', '7   chromedriver                        0x0000000108100583 chromedriver + 591235', '8   chromedriver                        0x00000001080edb53 chromedriver + 514899', '9   chromedriver                        0x00000001080c320e chromedriver + 340494', '10  chromedriver                        0x00000001080c4485 chromedriver + 345221', '11  chromedriver                        0x00000001085106db __gxx_personality_v0 + 307291', '12  chromedriver                        0x00000001085275cf __gxx_personality_v0 + 401231', '13  chromedriver                        0x000000010852d7ab __gxx_personality_v0 + 426283', '14  chromedriver                        0x000000010852893a __gxx_personality_v0 + 406202', '15  chromedriver                        0x0000000108504d81 __gxx_personality_v0 + 259841', '16  chromedriver                        0x0000000108544c78 __gxx_personality_v0 + 521720', '17  chromedriver                        0x0000000108544e01 __gxx_personality_v0 + 522113', '18  chromedriver                        0x000000010855c268 __gxx_personality_v0 + 617448', '19  libsystem_pthread.dylib             0x00007fff74375661 _pthread_body + 340', '20  libsystem_pthread.dylib             0x00007fff7437550d _pthread_body + 0', '21  libsystem_pthread.dylib             0x00007fff74374bf9 thread_start + 13', ''])
automatic login failed
 Reinitialize tvdatafeed with auto_login=False
you are using nologin method, data you access may be limited

++++++++++++++++

from tvDatafeed import TvDatafeed,Interval
from datetime import datetime
import argparse

username = 'XXX'
password = 'XXXXX'


parser = argparse.ArgumentParser(description='Stock Name')
parser.add_argument('--name', dest='name', type=str, help='Stock Name')

args = parser.parse_args()

#print(args.name)

#tv = TvDatafeed(username, password,auto_login=True)
tv = TvDatafeed(username, password)

nifty_index_data = tv.get_hist(symbol=args.name,exchange='NSE',interval=Interval.in_1_minute,n_bars=5000,fut_contract=1)
#nifty_index_data = tv.get_hist(symbol=args.name,exchange='NSE',interval=Interval.in_daily,n_bars=5000,fut_contract=1)
filename = args.name + '.csv'
print(filename)

nifty_index_data.drop(['symbol'], axis = 1,inplace = True)

nifty_index_data.to_csv(filename, sep=',', encoding='utf-8', header='true')

+++++++++++++++++

I have tried to delete the .tvdatafeed folder in $HOME.
Same Issue.

This issue happens if i do autologin , if i use auto_login false and enter in browser it works fine but need to deploy this script for getting continuous data on server so it will be difficult.

Reinstalled the latest version ,same issue.

Thanks
Saurabh

Error using tv = TvDatafeed(auto_login=False)

from tvDatafeed import TvDatafeed, Interval
tv = TvDatafeed(auto_login=False)


----> 4 tv = TvDatafeed(auto_login=False)

TypeError: __init__() got an unexpected keyword argument 'auto_login'

getting this error, am I doing something wrong here?

PermissionError & UnboundLocalError: local variable 'driver' referenced before assignment

i tried running first time and got following error. Also i have checked and changed permission as well but still getting same error

(tv) prathamesh@prathamesh-ThinkPad-X1-Carbon:~/Software/tvdatafeed-main$ python3 tv.py 

chromedriver not found. do you want to autoinstall chromedriver?? y/ny
Requirement already satisfied: chromedriver-autoinstaller in ./tv/lib/python3.8/site-packages (0.2.2)
error Message: '' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home

Traceback (most recent call last):
  File "/home/prathamesh/Software/tvdatafeed-main/tv/lib/python3.8/site-packages/selenium/webdriver/common/service.py", line 72, in start
    self.process = subprocess.Popen(cmd, env=self.env,
  File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
PermissionError: [Errno 13] Permission denied: '/home/prathamesh/.tv_datafeed/'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "build\bdist.win-amd64\egg\tvDatafeed\main.py", line 89, in __get_token
  File "/home/prathamesh/Software/tvdatafeed-main/tv/lib/python3.8/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__
    self.service.start()
  File "/home/prathamesh/Software/tvdatafeed-main/tv/lib/python3.8/site-packages/selenium/webdriver/common/service.py", line 86, in start
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: '' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "tv.py", line 8, in <module>
    tv=TvDatafeed(username, password, chromedriver_path=None)
  File "build\bdist.win-amd64\egg\tvDatafeed\main.py", line 176, in __init__
  File "build\bdist.win-amd64\egg\tvDatafeed\main.py", line 147, in __get_token
UnboundLocalError: local variable 'driver' referenced before assignment

Random ValueError: could not convert string to float: '}'

Hi,
When running this code:

tv=TvDatafeed(username, password, chromedriver_path="C:\\WebDriver\\bin\\chromedriver.exe", auto_login=False)
data=tv.get_hist(symbol='SE02Y',exchange="TVC",interval=Interval.in_daily, n_bars=100)

sometimes I get this error:

ValueError: could not convert string to float: '}' 

~\anaconda3\lib\site-packages\tvDatafeed\main.py in get_hist(self, symbol, exchange, interval, n_bars, fut_contract)
    474                 break
    475 
--> 476         return self.__create_df(raw_data, symbol)
    477 
    478 

~\anaconda3\lib\site-packages\tvDatafeed\main.py in __create_df(raw_data, symbol)
    353                     float(xi[7]),
    354                     float(xi[8]),
--> 355                     float(xi[9]),
    356                 ]
    357             )

ValueError: could not convert string to float: '}'

I cannot find a pattern that explains why sometimes it works and sometimes it doesn't. It looks just random.
When using different securities I don't have the same issue
Any help?
Thanks

price including dividends

Hello.

Is it possible to download stock prices including dividends? There are switch in right bortom - for example in moex:gazp.

Thank you

Permission Error

PermissionError Traceback (most recent call last)
~/anaconda3/envs/tv/lib/python3.9/site-packages/selenium/webdriver/common/service.py in start(self)
71 cmd.extend(self.command_line_args())
---> 72 self.process = subprocess.Popen(cmd, env=self.env,
73 close_fds=platform.system() != 'Windows',

~/anaconda3/envs/tv/lib/python3.9/subprocess.py in init(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, user, group, extra_groups, encoding, errors, text, umask)
950
--> 951 self._execute_child(args, executable, preexec_fn, close_fds,
952 pass_fds, cwd, env,

~/anaconda3/envs/tv/lib/python3.9/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, gid, gids, uid, umask, start_new_session)
1820 err_msg = os.strerror(errno_num)
-> 1821 raise child_exception_type(errno_num, err_msg, err_filename)
1822 raise child_exception_type(err_msg)

PermissionError: [Errno 13] Permission denied: '/home/x/.tv_datafeed/'

During handling of the above exception, another exception occurred:

WebDriverException Traceback (most recent call last)
~/anaconda3/envs/tv/lib/python3.9/site-packages/tvDatafeed/main.py in __webdriver_init(self)
247
--> 248 driver = webdriver.Chrome(
249 self.chromedriver_path, desired_capabilities=caps, options=options

~/anaconda3/envs/tv/lib/python3.9/site-packages/selenium/webdriver/chrome/webdriver.py in init(self, executable_path, port, options, service_args, desired_capabilities, service_log_path, chrome_options, keep_alive)
72 log_path=service_log_path)
---> 73 self.service.start()
74

~/anaconda3/envs/tv/lib/python3.9/site-packages/selenium/webdriver/common/service.py in start(self)
85 elif err.errno == errno.EACCES:
---> 86 raise WebDriverException(
87 "'%s' executable may have wrong permissions. %s" % (

WebDriverException: Message: '' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home

During handling of the above exception, another exception occurred:

UnboundLocalError Traceback (most recent call last)
/tmp/ipykernel_16052/1741820756.py in
----> 1 tv= TvDatafeed(auto_login=False)

~/anaconda3/envs/tv/lib/python3.9/site-packages/tvDatafeed/main.py in init(self, username, password, chromedriver_path, auto_login)
135
136 token = None
--> 137 token = self.auth(username, password)
138
139 if token is None:

~/anaconda3/envs/tv/lib/python3.9/site-packages/tvDatafeed/main.py in auth(self, username, password)
210
211 else:
--> 212 driver = self.__login(username, password)
213 if driver is not None:
214 token = self.__get_token(driver)

~/anaconda3/envs/tv/lib/python3.9/site-packages/tvDatafeed/main.py in __login(self, username, password)
150 def __login(self, username, password):
151
--> 152 driver = self.__webdriver_init()
153
154 if not self.__automatic_login:

~/anaconda3/envs/tv/lib/python3.9/site-packages/tvDatafeed/main.py in __webdriver_init(self)
258
259 except Exception as e:
--> 260 driver.quit()
261 logger.error(e)
262

UnboundLocalError: local variable 'driver' referenced before assignment

Issue to use this library in docker

Hello,
First of all thank you for sharing your work.

I would like to use it inside a docker container. However it crash because I can't answer the question for chromedriver.
Is there any solution?
"\n\ndo you want to install chromedriver automatically?? y/n\t"

Regards,

Thomas

Error launching Chrome to Sign In to Trading View

On Windows 11 Pro x64 using Visual Studio Code environment set with Anaconda Python 3.9 using https://www.youtube.com/watch?v=f76dOZW2gwI tutorial I typed the following. Using Google Chrome 64bit version 99.0.4844.82 installed through chocolately.

`
from tvDatafeed import TvDatafeed, Interval
import datetime
import logging

logging.basicConfig(level=logging.DEBUG)
tv = TvDatafeed(auto_login=False,)
`

The error I receive on the panel on the right is the following

INFO:tvDatafeed.main:refreshing tradingview token using selenium
DEBUG:tvDatafeed.main:launching chrome

You need to login manually

Press 'enter' to open the browser
opening browser. Press enter once lgged in return back and press 'enter'.

DO NOT CLOSE THE BROWSER
ERROR:tvDatafeed.main:expected str, bytes or os.PathLike object, not NoneType
WARNING:tvDatafeed.main:you are using nologin method, data you access may be limited`

Google Chrome does not even open, although I hit Enter twice on Visual Studio Code. Normally I use Brave as my default browser but switched to Google Chrome after the first error.

Please add threading to get data faster on bulk symbol data download

Thanks for this wonderful api, I am trying to download data for multiple scripts its working good but little slow, looking your support to get it faster... Please add threading or multiprocessing(whatever work to make it faster) to get data faster on bulk symbol data download continuously.

Trying to download live data for some analysis... I am downloading 10 -20 bars only for a single script...

Problem with a first run

Hi StreamAlpha,

I copied the code from pypi.org to have a test run. I have Python v3.8.7 in VSC on Windows 7. The TradingView account I am accessing is paid and I can manually download .CSV files.

As expected code asked me to install Chrome driver where I answered: yes and y. Than I got this error report:

(py_venv) PS C:\xxxx\Software\Python\Learning-00> python learn_TradingView_API.py

do you want to install chromedriver automatically?? yes

chromedriver not found. do you want to autoinstall chromedriver?? y/ny
Requirement already satisfied: chromedriver-autoinstaller in c:\xxxx\software\python\learning-00\py_venv\lib\site-packages (0.2.2)
WARNING: You are using pip version 21.0.1; however, version 21.1.1 is available.
You should consider upgrading via the 'c:\xxxx\software\python\learning-00\py_venv\scripts\python.exe -m pip install --upgrade pip' command.

DevTools listening on ws://127.0.0.1:62801/devtools/browser/2f669919-1c01-4f9a-b6d1-d3a2a5578c51
[0515/185937.550:ERROR:gpu_init.cc(426)] Passthrough is not supported, GL is swiftshader
[0515/185952.124:INFO:CONSOLE(103)] "not loaded module js/expected-language", source: https://in.tradingview.com/static/bundles/category.97d1c8165098806fabf1.js (103)
[0515/190006.910:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190027.799:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190029.401:INFO:CONSOLE(291)] "2021-05-15T18:00:29.399Z:Fetch:POST //telemetry.tradingview.com/site-free/report. TypeError: Failed to fetch", source: https://in.tradingview.com/static/bundles/category.97d1c8165098806fabf1.js (291)
[0515/190029.405:INFO:CONSOLE(291)] "2021-05-15T18:00:29.400Z:Fetch:POST /accounts/signin/. TypeError: Failed to fetch", source: https://in.tradingview.com/static/bundles/category.97d1c8165098806fabf1.js (291)
[0515/190033.337:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190033.743:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190037.433:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190039.316:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190039.711:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190041.113:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190041.116:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190044.403:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190046.845:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190049.205:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190049.211:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190049.213:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190049.455:INFO:CONSOLE(311)] "not loaded module js/expected-language", source: https://www.tradingview.com/static/bundles/main_chart.a9f6daaaa0064d2db822.js (311)
[0515/190050.957:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190050.960:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190055.857:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190110.264:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190116.542:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190117.506:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190120.037:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190120.044:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190128.832:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190128.834:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190129.857:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
[0515/190129.859:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
error local variable 'token' referenced before assignment
m326m{"session_id":"<0.31858.145>_fra2-charts-6-webchart-9@fra2-compute-6_x","timestamp":1621101693,"release":"registry:5000/tvbs_release/webchart:release_204-36","studies_metadata_hash":"556d4eed209eaf4dd892a1acc52823e6e67d1b7c","protocol":"json","javastudies":"javastudies-3.60_1327","auth_scheme_vsn":2,"via":"84.16.251.31:443"}
m41m{"m":"protocol_error","p":["wrong data"]}

ERROR:tvDatafeed.main:Connection is already closed.
Traceback (most recent call last):
File "learn_TradingView_API.py", line 65, in
nifty_data = objTV.get_hist(symbol='NIFTY',exchange='NSE',interval=Interval.in_1_hour,n_bars=1000)
File "C:\xxxx\Software\Python\Learning-00\py_venv\lib\site-packages\tvDatafeed\main.py", line 328, in get_hist
return self.__create_df(raw_data, symbol)
File "C:\xxxx\Software\Python\Learning-00\py_venv\lib\site-packages\tvDatafeed\main.py", line 244, in __create_df
out = re.search('"s":[(.+?)}]', raw_data).group(1)
AttributeError: 'NoneType' object has no attribute 'group'

What can possibly be wrong? Can you possibly suggest how to fix the above?

regards
DROBNJAK

UnboundLocalError: local variable 'driver' referenced before assignment

Could anyone help with this problem? Following is my code and it keep showing the error.

from tvDatafeed import TvDatafeed, Interval

username = 'myuser'
password = 'mypassword'

tv = TvDatafeed(username, password, chromedriver_path=None)
tv = TvDatafeed(auto_login=False)
tv.get_hist('AAPL', 'NASDAQ', interval=Interval.in_5_minute)

The error log in following,

Traceback (most recent call last):
  File "C:\Users\36900\AppData\Local\Programs\Python\Python39\lib\site-packages\tvDatafeed\main.py", line 248, in __webdriver_init
    driver = webdriver.Chrome(
  File "C:\Users\36900\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()
  File "C:\Users\36900\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\common\service.py", line 72, in start
    self.process = subprocess.Popen(cmd, env=self.env,
  File "C:\Users\36900\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 951, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\36900\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1360, in _execute_child
    args = list2cmdline(args)
  File "C:\Users\36900\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 565, in list2cmdline
    for arg in map(os.fsdecode, seq):
  File "C:\Users\36900\AppData\Local\Programs\Python\Python39\lib\os.py", line 822, in fsdecode
    filename = fspath(filename)  # Does type-checking of `filename`.
TypeError: expected str, bytes or os.PathLike object, not NoneType

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\36900\PycharmProjects\TradingViewAPI\data.py", line 8, in <module>
    tv = TvDatafeed(username, password, chromedriver_path=None)
  File "C:\Users\36900\AppData\Local\Programs\Python\Python39\lib\site-packages\tvDatafeed\main.py", line 137, in __init__
    token = self.auth(username, password)
  File "C:\Users\36900\AppData\Local\Programs\Python\Python39\lib\site-packages\tvDatafeed\main.py", line 212, in auth
    driver = self.__login(username, password)
  File "C:\Users\36900\AppData\Local\Programs\Python\Python39\lib\site-packages\tvDatafeed\main.py", line 152, in __login
    driver = self.__webdriver_init()
  File "C:\Users\36900\AppData\Local\Programs\Python\Python39\lib\site-packages\tvDatafeed\main.py", line 260, in __webdriver_init
    driver.quit()
UnboundLocalError: local variable 'driver' referenced before assignment

Process finished with exit code 1

Secret of Pivot Boss

Sir,
Initial_balance and wick_reversal are working fine, but while i am trying to run extreme_reveral there is a problem in import module ie. "from historical_data import get" this module is not find i am using visual studio code. pse help me how to solve this issue
the code is written below
from historical_data import get
import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt
import mplfinance as mpf

ohlc_data = get("TCS", "eq")
resampling_dict = {
"open": "first",
"high": "max",
"low": "min",
"close": "last",
"volume": "sum",
}
ohlc_data = ohlc_data.resample("30min", offset="15min").apply(resampling_dict).dropna()
with warm regards
ram niwas

How to extend the max-number of candles from 5k to 20k (allowed by premium subscribtion) ?

The provided below def get_hist loads maximum 5k candles.
May be you know the technique of how to receive 20 k candles(which is the maximum allowed ) for the premium subscription?

May be you could rewrite the cycle loading portions of candles to address separate periods of time?

` while True:
try:
result = self.ws.recv()
raw_data = raw_data + result + "\n"
except Exception as e:
logger.error(e)
break

        if "series_completed" in result:
            break

The whole function:
` def get_hist( self, symbol: str, exchange: str = "NSE", interval: Interval = Interval.in_daily, n_bars: int = 10, fut_contract: int = None, ) -> pd.DataFrame:
# self = self()
symbol = self.__format_symbol( symbol=symbol, exchange=exchange, contract=fut_contract )

    interval = interval.value

    # logger.debug("chart_session generated {}".format(self.chart_session))
    self.__create_connection()
    # self.__send_message("set_auth_token", ["unauthorized_user_token"])

    self.__send_message("set_auth_token", [self.token])
    self.__send_message("chart_create_session", [self.chart_session, ""])
    self.__send_message("quote_create_session", [self.session])
    
    self.__send_message( "quote_set_fields", [ self.session, "ch", "chp", "current_session", "description", "local_description", "language", "exchange", "fractional", "is_tradable",
            "lp", "lp_time", "minmov", "minmove2", "original_name", "pricescale", "pro_name", "short_name", "type", "update_mode", "volume", "currency_code", "rchp", "rtc", ], )

    self.__send_message( "quote_add_symbols", [self.session, symbol, {"flags": ["force_permission"]}] )
    self.__send_message("quote_fast_symbols", [self.session, symbol])

    self.__send_message( "resolve_symbol", [ self.chart_session, "symbol_1", '={"symbol":"' + symbol + '","adjustment":"splits","session":"extended"}', ], )
    self.__send_message( "create_series", [self.chart_session, "s1", "s1", "symbol_1", interval, n_bars], )

    raw_data = ""

    logger.debug(f"getting data for {symbol}...")
    while True:
        try:
            result = self.ws.recv()
            raw_data = raw_data + result + "\n"
        except Exception as e:
            logger.error(e)
            break

        if "series_completed" in result:
            break

    return self.__create_df(raw_data, symbol)`

Unable to login

Hi,
since today I've been getting an error (maybe it depends on the new TV layout):

from tvDatafeed import TvDatafeed,Interval
username = 'myuser'
password = 'mypassword'
tv=TvDatafeed(username, password, chromedriver_path=None)

returns:

error Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="overlap-manager-root"]/div/span/div[1]/div/div/div[1]/div[2]/div"}
  (Session info: headless chrome=92.0.4515.107)

you are using nologin method, data you access may be limited

Any help?
Thanks

Not working with username and password

Error in using ChromeDriver, Here is the error message

WARNING:tvDatafeed.main:error Message: session not created: This version of ChromeDriver only supports Chrome version 87 Current browser version is 91.0.4472.124 with binary path C:\Program Files\Google\Chrome\Application\chrome.exe

Working fine with no username and password

Chromedriver

Everytime I run the code it asks for the autoinstalling the chromedriver. What is to be done?

unexpected keyword argument 'dtype'

After following the instructions in detail. The first data feed test work. When I run with another asset getting error:

TypeError: init() got an unexpected keyword argument 'dtype'

Full Error:
DEBUG:tvDatafeed.main:getting data for NSE:NIFTY...
Traceback (most recent call last):
File "C:\Users\user1.conda\envs\tdview\lib\site-packages\IPython\core\interactiveshell.py", line 3369, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "", line 4, in <cell line: 4>
tvfeed.get_hist('NIFTY', 'NSE')
File "C:\Users\user1.conda\envs\tdview\lib\site-packages\tvDatafeed\main.py", line 504, in get_hist
return self.__create_df(raw_data, symbol)
File "C:\Users\user1.conda\envs\tdview\lib\site-packages\tvDatafeed\main.py", line 380, in __create_df
data = pd.DataFrame(
File "C:\Users\user1.conda\envs\tdview\lib\site-packages\pandas\core\frame.py", line 571, in init
columns = ensure_index(columns)
File "C:\Users\user1.conda\envs\tdview\lib\site-packages\pandas\core\indexes\base.py", line 5920, in ensure_index
return Index(index_like)
File "C:\Users\user1.conda\envs\tdview\lib\site-packages\pandas\core\indexes\base.py", line 363, in new
return cls(
TypeError: init() got an unexpected keyword argument 'dtype'

I'm using following code:

from tvDatafeed import TvDatafeed, Interval

tv = TvDatafeed()
tv.get_hist(symbol='AAPL', exchange='NASDAQ')

I already tried :

  • tv.clear_cache()
  • deleted .tv_datafeed folder from user profile

Problem seems with the index datatype but can't figure out how to fix it.

Please help with Error: Unable to locate element: {"method":"link text","selector":"Sign in"}

Code:
`from tvDatafeed import TvDatafeed, Interval

username = 'myuser'
password = 'mypassword'

tv = TvDatafeed(username, password, chromedriver_path=None)
tv = TvDatafeed(auto_login=False)
tv.get_hist('AAPL', 'NASDAQ', interval=Interval.in_5_minute)`

Added annaconda, using python 3.8x
When I try to run the code
I get the following error:

DevTools listening on ws://127.0.0.1:11794/devtools/browser/894d5c71-2cb1-4c8a-9548-088aa07b73a7
error Message: no such element: Unable to locate element: {"method":"link text","selector":"Sign in"}
(Session info: headless chrome=100.0.4896.75)

error when symbol name not found in database

Hi StreamAplha:
Firstly many many thanks for building this code. Its super helpful!! I am facing two issues in the code when the name of the symbol I sent is not in the list of securities of that exchange. With the very limited knowledge I have of python, I did try to modify your code a little, but I fell short and hence listing it out here.
First instead of throwing up an exception - which as you can see in the sample code will atleast allow me to debug and correct just returns a None
Second, it waits for almost 80 seconds to throw up the Error and hence holds up the other part of the code I am incorporating this into for that much time.

Sample code is

from tvDatafeed import TvDatafeed, Interval
import timeit

username = 'xxxx'
password = 'xxxx'


tv = TvDatafeed(username, password, chromedriver_path='./chromedriver')
security_name = 'BAJAJ-AUTO1!'
exchange = 'NSE'
number_of_bars = 1

starttime = timeit.default_timer()
try:
    data_recv = tv.get_hist(symbol=security_name, exchange=exchange, interval=Interval.in_5_minute, n_bars=number_of_bars)
    print(data_recv)
except AttributeError:
    print(f"error in getting data for {security_name}")
print("The time difference is :", timeit.default_timer() - starttime)

Output for the above code:

None
The time difference is : 81.035164397
ERROR:tvDatafeed.main:Connection to remote host was lost.
ERROR:tvDatafeed.main:no data, please check the exchange and symbol

Process finished with exit code 0

Output if just change the security_name to BAJAJ_AUTO1!

                               symbol    open  ...    close   volume
datetime                                       ...                  
2022-03-31 15:25:00  NSE:BAJAJ_AUTO1!  3666.7  ...  3677.05  32750.0

[1 rows x 6 columns]
The time difference is : 8.086900235

Process finished with exit code 0

developer branch unexpected keyworld argument 'auto_login' and main branch SSL error code 1

I was experiencing a similar issue. whose main syndrome is like this #1
ERROR:ssl_client_socket_impl.cc(960)] handshake failed; returned -1, SSL error code 1, net_error -100
So I follow the fix by upgrade my tvdatafeed to a developer branch
pip install --upgrade --no-cache-dir git+https://github.com/StreamAlpha/tvdatafeed.git@develop

However, it lead to another error
Traceback (most recent call last):
File "f:\tvpy\tvfeed.py", line 2, in
tv = TvDatafeed(auto_login=False)
TypeError: init() got an unexpected keyword argument 'auto_login'

All codes to produce this error

from tvDatafeed import TvDatafeed,Interval
tv = TvDatafeed(auto_login=False)

For this SSL error I don't know what caused it. Is it related to my using SSL proxy?
If so, how do I fix it?

Error thrown when downloading futures?

Hi,

Can you please check this error urgently?

Delay going to cause me a huge gap in the data I am collecting.

About a week ago I downloaded 100s of symbols from TradingView. And even now I can download all the stocks, indices, etc. But suddenly it is refusing to download S&P 500 E-mini (ES1!, YM1!, etc.) and all the other futures, although it was downloading the same symbol just fine a week ago. Is it possible that TradingView changed the future symbols?

Please have a look:

Exception has occured: AttributeError:
ERROR:tvDatafeed.main:Connection to remote host was lost.
Traceback (most recent call last):
File "trade_1_download_dpALL_v0.00.py", line 269, in
dfDownloadedPricesTable = objTradingView.get_hist(symbol= symbol["symbol"], exchange= symbo
l["exchange"], interval= Interval.in_1_minute, n_bars= 5000)
File "C:\Users\Dejan Corovic.platformio\penv\lib\site-packages\tvDatafeed\main.py", line 334
, in get_hist
return self.__create_df(raw_data, symbol)
File "C:\Users\Dejan Corovic.platformio\penv\lib\site-packages\tvDatafeed\main.py", line 250
, in __create_df
out = re.search('"s":[(.+?)}]', raw_data).group(1)
AttributeError: 'NoneType' object has no attribute 'group'

regards,
DROBNJAK

Couldn't install (upgrade from v1.0.4)

Dear all.
Unfortunately, I couldn't install (upgrade from v1.0.4) this lib with
pip install --upgrade --no-cache-dir git+https://github.com/StreamAlpha/tvdatafeed.git
:(

The Error message occurred as follows:
(base) Man@MacBook-Pro-ght-340 ~ % pip install --upgrade --no-cache-dir git+https://github.com/StreamAlpha/tvdatafeed.git
Collecting git+https://github.com/StreamAlpha/tvdatafeed.git
Cloning https://github.com/StreamAlpha/tvdatafeed.git to /private/var/folders/qt/4wsb0cvd637_6fk9m951hdrc0000gn/T/pip-req-build-kjhnth9b
Running command git clone -q https://github.com/StreamAlpha/tvdatafeed.git /private/var/folders/qt/4wsb0cvd637_6fk9m951hdrc0000gn/T/pip-req-build-kjhnth9b
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
WARNING: Discarding git+https://github.com/StreamAlpha/tvdatafeed.git. Command errored out with exit status 1: git clone -q https://github.com/StreamAlpha/tvdatafeed.git /private/var/folders/qt/4wsb0cvd637_6fk9m951hdrc0000gn/T/pip-req-build-kjhnth9b Check the logs for full command output.
ERROR: Command errored out with exit status 1: git clone -q https://github.com/StreamAlpha/tvdatafeed.git /private/var/folders/qt/4wsb0cvd637_6fk9m951hdrc0000gn/T/pip-req-build-kjhnth9b Check the logs for full command output.

volume is coming in exponential format .

Hi , Sorry to bother you again .
volume is coming in exponential format for big numbers , I converted it into float but still its coming in exponential format .
please find the screenshot ,
volume

Another Chrome Driver issue

I am using the pycharm IDE, and I am continually getting the "do you want to install chromedriver?? y/n" prompt, even after having installed it. The code does not work after that. Suggestions?

Thanks!

nonlogin method issue on Amazon web services

error Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="overlap-manager-root"]/div/span/div[1]/div/div/div[1]/div[2]/div"}
(Session info: headless chrome=91.0.4472.101)

you are using nologin method, data you access may be limited

i am running script on aws with ubuntu running. Above error is reflecting on terminal. However on my local machine script works fine.. any reason why this is happening? do i need to install any libraries?

Undocumented parameter fut_contract

Hi

I found this parameter for get_hist() method:

fut_contract: int | None = None) -> DataFrame

I don't understand how is it used. Can you please explain.

regards
DROBNJAK

Difference in ema values

Hey dude, From youtube...
I have downloaded latest data for nifty current month futures and plotted ema(20) on the close using thaat data and ta-lib. I am still not getting values as I see them on tradingview web. The simple code I wrote for this is below. Also, find attached a csv file where the values of ema calculation are stored and then I crosschecked it with TODAYS nifty futures data from tradingview web. Please just open csv file with excel and scroll down to check the same.

Let me know if I have done something horribly wrong...

from tvDatafeed import TvDatafeed, Interval
import pandas as pd
import talib as ta

tv = TvDatafeed()

def fut_snapshot(filename='sym.txt', timeframe='in_15_minute', n_bars=100, fut_contract=1):
    with open(filename) as f:
        line  = f.read().splitlines() # this file sym.txt only has NIFTY symbol in it
        for symbol in line:
            df = tv.get_hist(symbol, 'NSE', interval=Interval[timeframe], n_bars=n_bars, fut_contract=fut_contract)
            df.to_csv(f'{symbol}.csv')

            print(f'{symbol} downloaded and saved')

# fut_snapshot(n_bars=2000)

def ema_calc(filename='NIFTY.csv'):
    
    df = pd.read_csv(filename)
    symbol = 'NIFTY'
    # EMA 20
    df['ema_20'] = ta.EMA(df['close'], timeperiod=20)
    df.to_csv(f'{symbol}_ema.csv')


# ema_calc()

NIFTY_ema.csv

Option to Download Out-of-the-Hours Intraday Data

Hi,

Sorry to bother you again.

I've tried downloading 1-hour bars and I noticed that it only noticed that your library only downloads the main market session, during working hours. TradingView actually allows downloading out-of-the-hours sessions, when markets are closed.

The problem with the current setup is that it creates gaps in the data between sessions and these gaps then screw up indicators, as well as stop-losses. With automatic trading, one can place orders during out-of-the-hours sessions and close position, but he can not test that if there are gaps in the data.

Would it be possible to provide an option in your downloading method where one can choose if he wants or doesn't want out-of-the-hours data to be downloaded?

best regards
DROBNJAK

enhancement

Can we modify this API to also get financials like overview, Income statement, cash flow, and statistical data?
It would really help for creating some screeners.

Stocks and Indices OK, but Futures and Forex blow up

I am having problems downloading Futures and Forex. Stocks and Indices work fine. Here is the code:

I drilled down that problem is with the names of exchanges. For example for ES E-Mini exchange is CME_MINI, not CME. But the problem is FXCM forex exchange, the name is correct but the connection is refused. Do you possibly have a list of exchange tokens that TradingView's APIs are using?

TEST: STOCKS ... OK

print('\n\n', 'MSFT-NASDAQ is OK.')

dfTable = objTV.get_hist(symbol= 'MSFT', exchange= 'NASDAQ', interval= Interval.in_1_minute, n_bars=5000)

print(dfTable)

test: INDICES ... OK

print('\n\n', 'IMOEX-MOEX is OK.')

dfTable = objTV.get_hist(symbol= 'IMOEX', exchange= 'MOEX', interval= Interval.in_1_minute, n_bars=5000)

print(dfTable)

test: FUTURES ... OK

print('\n\n', 'ES1!-CME fails?')

dfTable = objTV.get_hist(symbol= 'ES1!', exchange= 'CME_MINI', interval= Interval.in_1_minute, n_bars=5000)

print(dfTable)

TEST: FOREX ... fail

print('\n\n', 'EURGBP-FXCM fails?')
dfTable = objTV.get_hist(symbol= 'EURGBP', exchange= 'FXCM', interval= Interval.in_1_minute, n_bars=5000)
print(dfTable)

And here are the errors that I am getting:

m328m{"session_id":"<0.5778.6401>_fra2-charts-32-webchart-6@fra2-compute-32_x","timestamp":1623721532,"release":"registry:5000/tvbs_release/webchart:release_204-36","studies_metadata_hash":"03f4e0fbdc9d0b595f5ee8037bed2288b28ccbdd","protocol":"json","javastudies":"javastudies-3.60_1327","auth_scheme_vsn":2,"via":"84.16.253.69:443"}
m82m{"m":"series_loading","p":["cs_prgbrtoohnho","s1","s1",1623721532],"t":1623721532}m74m{"m":"qsd","p":["qs_ugjmryrxsyxm",{"n":"FXCM:EURGBP","s":"error","v":{}}]}m98m{"m":"symbol_error","p":["cs_prgbrtoohnho","symbol_1","invalid symbol",1623721532],"t":1623721532}m140m{"m":"series_error","p":["cs_prgbrtoohnho","s1","s1","resolve error","fra2-charts-32-webchart-6@fra2-compute-32",1623721532],"t":1623721532}
m4m~~h1
m4m~~h2
m4m~~h3
m4m~~h4
m4m~~h5
m4m~~h6
m4m~~h7

ERROR:tvDatafeed.main:Connection is already closed.
Traceback (most recent call last):
File "learn_TradingView_API_v1.00.py", line 87, in
dfTable = objTV.get_hist(symbol= 'EURGBP', exchange= 'FXCM', interval= Interval.in_1_minute, n_bars=5000)
File "C:\Work D-PLUS-07\Software\Python\Learning-00\py_venv\lib\site-packages\tvDatafeed\main.py", line 333, in get_hist
return self.__create_df(raw_data, symbol)
File "C:\Work D-PLUS-07\Software\Python\Learning-00\py_venv\lib\site-packages\tvDatafeed\main.py", line 249, in __create_df
out = re.search('"s":[(.+?)}]', raw_data).group(1)
AttributeError: 'NoneType' object has no attribute 'group'

open the issue again , mxc not working .

Hi ,
I am using all good credentials , it works for equity .
it works for commodity too , but only when exchange is not given .
its not working when "MCX" is given as exchange , please find the screen shot , error are as usual .
mcx_error

File "C:\Python\lib\site-packages\tvDatafeed\main.py", line 335, in get_hist
return self.__create_df(raw_data, symbol)
File "C:\Python38\lib\site-packages\tvDatafeed\main.py", line 251, in __create_df
out = re.search('"s":[(.+?)}]', raw_data).group(1)
AttributeError: 'NoneType' object has no attribute 'group'
m329m{"session_id":"<0.13198.3653>_hkg1-charts-6-webchart-9@hkg1-compute-6_x","timestamp":1625298449,"release":"registry:5000/tvbs_release/webchart:release_204-45","studies_metadata_hash":"8a46abeb53a04396e3f024f9513b546b2459751f","protocol":"json","javastudies":"javastudies-3.60_1429","auth_scheme_vsn":2,"via":"45.135.231.119:443"}
m82m{"m":"series_loading","p":["cs_mgcyhzvxxpfr","s1","s1",1625298449],"t":1625298449}m115m{"m":"qsd","p":["qs_gbjgfqdnhlll",{"n":"MCX:NATURALGAS1!","s":"permission_denied","v":{"alternative":"mcx_free"}}]}m120m{"m":"symbol_error","p":["cs_mgcyhzvxxpfr","symbol_1","permission denied","group","mcx_free",1625298449],"t":1625298449}m138m{"m":"series_error","p":["cs_mgcyhzvxxpfr","s1","s1","resolve error","hkg1-charts-6-webchart-9@hkg1-compute-6",1625298449],"t":1625298449}m420m{"m":"qsd","p":["qs_gbjgfqdnhlll",{"n":"MCX:NATURALGAS1!","s":"ok","v":{"update_mode":"streaming","type":"futures","short_name":"NATURALGAS1!","pro_name":"MCX:NATURALGAS1!","pricescale":10,"original_name":"MCX:NATURALGAS1!","minmove2":0,"minmov":1,"language":"hi","is_tradable":true,"fractional":false,"exchange":"MCX","description":"NATURAL GAS FUTURES (CONTINUOUS: CURRENT CONTRACT IN FRONT)","currency_code":"INR"}}]}
m4m~~h1
m4m~~h2
m4m~~h3
m4m~~h4
m4m~~h5
m4m~~h6
m4m~~h7

How can I install Selenium driver on ReplIt?

I want to run my TradingView download code from an online Python code hosting service called ReplIt.com.

If one needs to install Chromium browser in order to get that Selenium driver, that one can forget about running his code from Python hosted online ... Is there any workaround so one can get Selenium without installing Chromium?

Can that Selenium be replaced with something that doesn't need Chromium? Why is Selenium needed at all, when Yahoo Finance Python library can work without Selenium?

Message: unknown error: Chrome failed to start: exited abnormally. (unknown error: DevToolsActivePort file doesn't exist)

The full error is below. Do you know what this means? Is it because I am using chromium instead of chrome? Or perhaps a firewall issue?

$ python historical_data.py 
INFO:tvDatafeed.main:refreshing tradingview token using selenium
DEBUG:tvDatafeed.main:launching chrome



You need to login manually

 Press 'enter' to open the browser 

opening browser. Press enter once lgged in return back and press 'enter'. 

DO NOT CLOSE THE BROWSER
DEBUG:selenium.webdriver.remote.remote_connection:POST http://localhost:55421/session {"capabilities": {"firstMatch": [{}], "alwaysMatch": {"browserName": "chrome", "goog:loggingPrefs": {"performance": "ALL"}, "pageLoadStrategy": "normal", "goog:chromeOptions": {"extensions": [], "args": ["--disable-gpu", "--user-data-dir=/home/user/snap/chromium/common/chromium/Default"]}}}, "desiredCapabilities": {"browserName": "chrome", "goog:loggingPrefs": {"performance": "ALL"}, "pageLoadStrategy": "normal", "goog:chromeOptions": {"extensions": [], "args": ["--disable-gpu", "--user-data-dir=/home/user/snap/chromium/common/chromium/Default"]}}}
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): localhost:55421
DEBUG:urllib3.connectionpool:http://localhost:55421 "POST /session HTTP/1.1" 500 365
DEBUG:selenium.webdriver.remote.remote_connection:Finished Request
Traceback (most recent call last):
  File "/home/user/.virtualenvs/trading/lib/python3.7/site-packages/tvDatafeed/main.py", line 269, in __webdriver_init
    self.chromedriver_path, desired_capabilities=caps, options=options
  File "/home/user/.virtualenvs/trading/lib/python3.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__
    service_log_path, service, keep_alive)
  File "/home/user/.virtualenvs/trading/lib/python3.7/site-packages/selenium/webdriver/chromium/webdriver.py", line 99, in __init__
    options=options)
  File "/home/user/.virtualenvs/trading/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 268, in __init__
    self.start_session(capabilities, browser_profile)
  File "/home/user/.virtualenvs/trading/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 359, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/home/user/.virtualenvs/trading/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "/home/user/.virtualenvs/trading/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /home/user/.tv_datafeed/chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Stacktrace:
#0 0x650faa878e89 <unknown>


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "historical_data.py", line 12, in <module>
    tv = TvDatafeed(auto_login=False)
  File "/home/user/.virtualenvs/trading/lib/python3.7/site-packages/tvDatafeed/main.py", line 145, in __init__
    token = self.auth(username, password)
  File "/home/user/.virtualenvs/trading/lib/python3.7/site-packages/tvDatafeed/main.py", line 220, in auth
    driver = self.__login(username, password)
  File "/home/user/.virtualenvs/trading/lib/python3.7/site-packages/tvDatafeed/main.py", line 160, in __login
    driver = self.__webdriver_init()
  File "/home/user/.virtualenvs/trading/lib/python3.7/site-packages/tvDatafeed/main.py", line 280, in __webdriver_init
    driver.quit()
UnboundLocalError: local variable 'driver' referenced before assignment

ERROR:tvDatafeed.main:expected str, bytes or os.PathLike object, not NoneType

Hello

I installed Python version 3.9.8:
image
The same as in the movie:
https://www.youtube.com/watch?v=kENccs0CW18

In created virtual env and i installed TvDatafeed with:
pip install --upgrade --no-cache-dir git+https://github.com/StreamAlpha/tvdatafeed.git

My pip freeze looks like this:

async-generator==1.10
attrs==21.4.0
certifi==2021.10.8
cffi==1.15.0
chromedriver-autoinstaller==0.3.1
cryptography==37.0.2
h11==0.13.0
idna==3.3
numpy==1.22.3
outcome==1.1.0
pandas==1.4.2
pycparser==2.21
pyOpenSSL==22.0.0
PySocks==1.7.1
python-dateutil==2.8.2
pytz==2022.1
selenium==4.1.3
six==1.16.0
sniffio==1.2.0
sortedcontainers==2.4.0
trio==0.20.0
trio-websocket==0.9.2
tvdatafeed==1.2.1
urllib3==1.26.9
websocket-client==1.3.2
wsproto==1.1.0

Screen of how i try to login:
image

After i clicked "enter" browser is not opening. Additionally i checked directory:
C:\Users<name>.tv_datafeed\chrome and it is empty.

Is there any fixed for this?

Login with password don't work as well:

tv = TvDatafeed(
    username=environ.get('tv_user'),
    password=environ.get('tv_password'),
    chromedriver_path=None
)

Cheers

selecting date range

hi, I think the easiest way to overcome the 5000 candle limit is by allowing the user to specify the time period ...can anyone tell me how to do it.

chromedriver not found. do you want to autoinstall chromedriver?

with this new version , getting this .
chromedriver not found. do you want to autoinstall chromedriver?
after entering "Y"
getting "Requirement already satisfied: chromedriver-autoinstaller in c:\python38\lib\site-packages (0.2.2)"
then nothing , not sure what is this ?

is it possible that chromedriver module is installed when the main module is installed with pip install .

Incorrect date

Hi,
I have a strange issue with daily data of Japanese futures: the data I get in Python is back shifted by 1 day, compared to the data I see from the chart on the website:

So, for example for OSE:NKVIM2021:

My code is:

from tvDatafeed import TvDatafeed,Interval
tv = TvDatafeed(chromedriver_path="C:\\WebDriver\\bin\\chromedriver.exe")
data= tv.get_hist(symbol='NKVIM2021',exchange='OSE',interval=Interval.in_daily,n_bars=100)

(I have the same issue if I access with username and password)

website
python

When timeframe interval is 1 hour, the data looks correct.

ERROR:tvDatafeed.main:Connection is already closed.

Hi StreamAlpha,

I am getting this error "ERROR:tvDatafeed.main:Connection is already closed" for some sources.
e.g:

outputData=tv.get_hist('EURUSD','FXCM',Interval.in_1_minute,n_bars=2000)

The above code line runs into the error mentioned above. Though If I change the source it works as expected. Please help me out in issue since particular sources are very important for me. I am facing similar issue with FOREX.com:DJI.

Attaching stacktrace for your assistance:

AttributeError                            Traceback (most recent call last)
<ipython-input-18-a01576d86815> in <module>
----> 1 outputData=tv.get_hist('EURUSD','FXCM',Interval.in_1_minute,n_bars=2000)

F:\Anaconda\lib\site-packages\tvDatafeed\main.py in get_hist(self, symbol, exchange, interval, n_bars, fut_contract)
    474                 break
    475 
--> 476         return self.__create_df(raw_data, symbol)
    477 
    478 

F:\Anaconda\lib\site-packages\tvDatafeed\main.py in __create_df(raw_data, symbol)
    339     @staticmethod
    340     def __create_df(raw_data, symbol):
--> 341         out = re.search('"s":\[(.+?)\}\]', raw_data).group(1)
    342         x = out.split(',{"')
    343         data = list()

AttributeError: 'NoneType' object has no attribute 'group'

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.