Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot log in #32

Open
andreasklinar opened this issue Nov 26, 2023 · 20 comments
Open

Cannot log in #32

andreasklinar opened this issue Nov 26, 2023 · 20 comments

Comments

@andreasklinar
Copy link

Hi,

it seems like the libarary needs to be udpated. I get the following error when trying to log in:

error while signin
you are using nologin method, data you access may be limited

Thanks!

@liebig
Copy link

liebig commented Dec 3, 2023

If you log in via the Trading View website, do you have to fill in a Google Captcha? If so, this is the problem when logging in with this library. In my fork of this library I persist the token on the file system and load it when using it. So you could take the token from the login request on the Trading View website and save it in token.txt and use the library again.

Or you can wait a few days, login via webrowser and hopefully the Google Captcha is gone.

@Davejavu4u
Copy link

@liebig I'm experiencing the same issue. Can you provide more info on how to find the token?

@traderjoe1968
Copy link

traderjoe1968 commented Dec 18, 2023

See Pull Request (#29) for a method to login

@gopal86
Copy link

gopal86 commented Jan 24, 2024

@liebig I am still having issue logging in. Can you elaborate on it?

@gopal86
Copy link

gopal86 commented Jan 24, 2024

@traderjoe1968 I installed your commit, however the problem persist. Could you help out?

@liebig
Copy link

liebig commented Jan 24, 2024

@liebig I am still having issue logging in. Can you elaborate on it?

Have a look here: liebig@873713a#commitcomment-137518936

@gopal86
Copy link

gopal86 commented Jan 24, 2024

@liebig thank you, I followed those steps and save auth_token in token.txt in my project's root folder. However, now I am getting this error: [Errno 2] No such file or directory: ~/.local/share/tvdata/token.2fa

Could you guide me on this?

@traderjoe1968
Copy link

traderjoe1968 commented Jan 24, 2024

Ensure you create the 'TvDataFeed' object correctly.
you need to run your code within a terminal. When you are prompted for your 2FA. Open 2FA app and type code into terminal.

I just tested it at mine end - still works.

If it does not work check you 2FA is synchronised with TradingView. Log out of TradingView website and re-login. It should ask you for your 2FA code.

# get credentials for tradingview
username = "your username"
password = "your password"
# initialize tradingview
tv = TvDatafeed(username=username, password=password, pro=True)

2fa0

here is example code to use

import os
import pandas as pd
from datetime import datetime as dt
from pathlib import Path
from tvDatafeed import TvDatafeed, Interval
import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(message)s",
    handlers=[
        logging.FileHandler(f"tvdata.log", mode="w"),
        logging.StreamHandler(),
    ],
)

dataPath = r"Data"
# If no such folder exists, create an empty folder
if not os.path.exists(dataPath):
    os.mkdir(dataPath)
    logging.info(f"creating Directory {dataPath}")

def downloadData(Sym, Exchange):
    try:
        df = tv.get_hist(
            Sym, Exchange, Interval.in_5_minute, n_bars=5000, extended_session=True
        )
    except Exception:
        logging.exception("TvDataFeed Error")
        raise
    df.insert(0, "date", df.index.date)
    df.insert(1, "time", df.index.time)
    df.reset_index(inplace=True)
    del df["datetime"]
    del df["symbol"]

    return df

# get credentials for tradingview
username = "your username"
password = "your password"
# initialize tradingview
tv = TvDatafeed(username=username, password=password, pro=True)

if __name__ == "__main__":
    symList = [
        ("SPY", "AMEX"),
    ]

    logging.info("Starting import...")
    try:
        for i, sym in enumerate(symList):
                logging.info(f"Processing {sym}")
                info = tv.search_symbol(sym[0], sym[1])
                try:
                    data = downloadData(sym[0], sym[1])
                except Exception:
                    continue
                filename = os.path.join(dataPath, sym[0] + ".csv")
                logging.info(f"Writing {filename}")
                data.to_csv(
                    filename,
                    columns=[
                        "date",
                        "time",
                        "open",
                        "high",
                        "low",
                        "close",
                        "volume",
                    ],
                    index=False,
                )
                
        logging.info("Finished Import")

    except Exception:
        logging.exception()

@gopal86
Copy link

gopal86 commented Jan 24, 2024

@traderjoe1968 My 2FA is off

tv = TvDatafeed(username=username, password=password, pro=True), I am getting unexpected keyword argument 'pro' when I change main.py from your PR.

After removing pro, I am still getting error while signin.

@traderjoe1968
Copy link

traderjoe1968 commented Jan 24, 2024 via email

@gopal86
Copy link

gopal86 commented Jan 25, 2024

@traderjoe1968 yeah, I just updated main.py with first commit of 2fa, not the other 3 commits. I updated the main.py with the latest commit, still unable to login.

I also cloned your repo link, and it gives the same error as well.

@traderjoe1968
Copy link

traderjoe1968 commented Jan 25, 2024

Back to checking you TradingView profile and settings
a) Do you have a "Plus" or "Premium" or higher subscription ?
b) When you logout of TrandingView and re-login Are you prompted to enter a 2FA code ??

If a) & b) are good then try demo code above and see if you can debug and get why it is failing - look at response coming back in def __auth(self, username, password): in 2FA section.

I know the code works for me and others - so not much else I can do to help

@gopal86
Copy link

gopal86 commented Jan 25, 2024

@traderjoe1968:

A.) Yes, I have a "Plus" subscription.
B.) My 2FA is off. Should I turn it on?

Screenshot from 2024-01-25 00-40-26

@traderjoe1968
Copy link

The original code assumed you would get a token back. See original code in main.py.
All I did was add additional code to detect and handle the 2FA_Required in response.

So if you are still not able to login without a putting in a 2FA code then it seems the TradingView requires it.
You are welcome to put a break point in the code and see the response text. See if you can find a problem.

If you just want to get it working then setup 2FA app - follow instructions on TradingView. It should then work ?

def __auth(self, username, password):
     ...
     ...
                        if "2FA_required" in response.text:
                            response = s.post(url=self.__sign_in_totp, data={"code": self.__getcode()}, headers=self.__signin_headers)
                            token = response.json()['user']['auth_token']
                            with open(tokendata, 'w') as f:
                                    f.write(token)
    ...
    ...

@gopal86
Copy link

gopal86 commented Jan 25, 2024

@traderjoe1968 When I print response.text, I get:

{"error":"Please confirm that you are not a robot by clicking the captcha box.","code":"recaptcha_required"}

I believe @liebig solved it and explained it here, however even when I extract the auth_code, I get [Errno 2] No such file or directory: ~/.local/share/tvdata/token.2fa error. Do you have any thoughts on it?

I don't think setting up 2FA will help? Anyway I will try it.

@traderjoe1968
Copy link

If you have the token string just create the file with a text editor in ~/.local/share/tvdata/token.2fa and paste the token in.
Run again and it should log in

@gopal86
Copy link

gopal86 commented Jan 25, 2024

@traderjoe1968 I did that and I was getting the error:

self.__delete_token() TypeError: __delete_token() missing 1 required positional argument: 'self'

I commented out the delete section for now as it was just deleting the token, then I am getting the error:
ERROR:tvDatafeed.main:Connection to remote host was lost.

@traderjoe1968
Copy link

traderjoe1968 commented Jan 25, 2024

The reason your file is being deleted is because it is not a valid token for the connection - if the code fails to log into TrandingView then it assume the token is no longer valid and asks you to log in again.

Did you setup 2FA and test it by logging out and in multiple times by logging in via web browser !! If you don't get the enter code box then it's not setup properly
2fa0

This is real simple code - do some debugging

  1. put a break point on tokendata.parent.mkdir(parents=True, exist_ok=True)
  2. see what the path that your OS is pointing to for the token file (Win, macos, linux are all different)
  3. step code to next
  4. open aa terminal and go to the path in tokendata you should see a folder
tokendata = Path(user_data_dir(appname="tvdata", appauthor=""), "token.2fa")
tokendata.parent.mkdir(parents=True, exist_ok=True) 
  1. Put a break point on if "2FA_required" in response.text: and step through the code executing.
    check the response and the token coming back.
if "2FA_required" in response.text:
                            response = s.post(url=self.__sign_in_totp, data={"code": self.__getcode()}, headers=self.__signin_headers)
                            token = response.json()['user']['auth_token']
                            with open(tokendata, 'w') as f:
                                    f.write(token)
                        else:
                            token = response.json()['user']['auth_token']
  1. Continue executing code
  2. open aa terminal and go to the path in tokendata you should see a the token.2fa

IF you get "code":"recaptcha_required" in response text then you will need to wait until the timeout period for captcha.

You can try again the "@liebig solved it and explained it here," process but I am not sure it will work as the token is unique to each application that connects in (I don't think you can take the web browser token and use it with python script - I could be wrong)

There is no more I can help you with - please just debug this yourself. If you find that there are improvements / workarounds etc add to the PR or raise another PR

@gopal86
Copy link

gopal86 commented Jan 25, 2024

@traderjoe1968 Sure, I'll will be debugging this. Thank you so much for all the help, patience and time. I'll try with 2FA and see how it goes!

@AssetOverflow
Copy link

AssetOverflow commented Feb 16, 2024

traderjoe1968
@traderjoe1968
if i have a Premium subscription, shouldn't i get 20k? is there a way to specify Premium? It seems like its working and all, but i'm only getting 11,300 bars.. is it just not providing enough time to fetch all the bars maybe? or could that not be it..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants