示例#1
0
def getLoginHtml():
    app_session = accessToken.SessionModel(app_id, app_secret) 
    response = app_session.auth()
    authorization_code = response['data']['authorization_code']
    app_session.set_token(authorization_code)
    url =app_session.generate_token()
    return requests.get(url).text
def generate_session(app_id, app_secret):
    app_session = accessToken.SessionModel(app_id, app_secret)
    response = app_session.auth()

    if response["code"] != 200:
        print response
        sys.exit()

    auth_code = response["data"]["authorization_code"]

    app_session.set_token(auth_code)

    generateTokenUrl = app_session.generate_token()
    webbrowser.open(generateTokenUrl, new=1)

    token = input(
        "Paste the token here")  #acces token is copied from the redirected url
    with open("accesstoken.txt", "w") as f:
        f.write(token)  #token is saved as txt for further use

    is_async = False  #(By default False, Change to True for asnyc API calls.)

    fyers = fyersModel.FyersModel(is_async)
    profile = fyers.get_profile(token=token)

    print(profile)
示例#3
0
    def _login(self, **kwargs):
        import time

        app_id = kwargs.pop("app_id")
        app_secret = kwargs.pop("app_secret")
        username = kwargs.pop("username")
        password = kwargs.pop("password")
        dob = kwargs.pop("dob")
        app_session = accessToken.SessionModel(app_id, app_secret)
        response = app_session.auth()
        auth_code = response["data"]["authorization_code"]
        app_session.set_token(auth_code)
        url = app_session.generate_token()
        # Initiating the driver to log in
        driver = webdriver.Chrome()
        driver.get(url)
        # Auto login
        login_form = WebDriverWait(driver, 45).until(
            EC.presence_of_element_located((By.ID, "myForm")))
        login_form.find_elements_by_id("fyers_id")[0].send_keys(username)
        login_form.find_elements_by_id("password")[0].send_keys(password)
        login_form.find_elements_by_class_name("login-dob")[0].click()
        login_form.find_elements_by_id("dob")[0].send_keys(dob)
        driver.find_element_by_id("btn_id").click()
        time.sleep(2)
        WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.NAME, "email")))
        url = driver.current_url
        token = self.get_token(url)
        self._token = token
        with open("fyers-token.tok", "w") as f:
            f.write(token)
        driver.close()
示例#4
0
def getauthToken(appId, redirect_uri):
    functionName = "getauthToken"
    """
        :param app_id: "XXXXXXXXXXX"
        :param redirect_url: "https://XXXXXX.com"
		 1. This function open this url in the browser.
		 2. This will ask you to login and will ask you to approve the app if it is not approved already.
		 3. Once that is done, it will redirect to a url (added while app creation) with the auth_code. The url will look like
		    https://www.google.com/?auth_code=eyJ0eXAiOiXXXXXGciOiJIUzI1NiJ9.eyXXXXXXXXXXXXXInN1YiI6ImF1dGhDb2XXXXXXXXXXXXXXXXXX2lkIjoiQjhQV0xWSDhUNiIsImlzcyI6ImFwaS5sb2dpbi5meWVycy5pbiIsImF1ZCI6WyJ4OjAiLCJ4OjEiLCJ4OjIiXSwidXVpZCI6ImZhOGNhYjE3ZWU4OTQzMGRhZjA1YWUxNDI2YWVkYzI4IiwiaXBBZGRyIjoiMjIzLjIzMy40Mi40NiIsImRpc3BsYXlfbmFtZSI6IkRQMDA0MDQiLCJpYXQiOjE1OTM1ODYzNzEsIm5iZiI6MTU5MzU4NjM3MX0.IMJHzQGHQgyXt_XN0AgDrMN1keR4qolFFKO6cyXTnTg&user_id=DP00404
		 4. You have to take the auth_code from the url and use that token in your generate_access_token function.
	"""
    response_type = "code"
    grant_type = "authorization_code"
    # creating an instance appSession to generate the auth code by passing app id and redirect url as parameter
    appSession = accessToken.SessionModel(client_id=appId,
                                          redirect_uri=redirect_uri,
                                          response_type=response_type,
                                          grant_type=grant_type,
                                          state="state",
                                          scope="",
                                          nonce="")

    # The variable `generateTokenUrl` will have a url like https://uat-api.fyers.in/api/dev/generate-authcode?appId=B8PXXXH8T6&redirectUrl=https%3A%2F%2Fgoogle.com
    generateTokenUrl = appSession.generate_authcode()

    # This command is used to open the url in default system brower
    webbrowser.open(generateTokenUrl, new=1)
 def get_session_url(self):
     self.session = accessToken.SessionModel(client_id=self.app_id,
                                         secret_key=self.app_secret,
                                         redirect_uri=self.redirect_url,
                                         response_type='code', 
                                         grant_type='authorization_code')
     self.url = self.session.generate_authcode()
     print('generating url successful')
def generate_token_url(app_id, secret_id):
    """ This function will generate the url which contains the Access Token

    Parameters:
    -----------
    app_id: string
        App Id is generated when we create an app in Fyers API. Saved in .env file as APPID
    secret_id: string
        Secret Id is generated when we create an app in Fyers API. Saved in .env file as SECRETID

    Returns:
    --------
    url_with_token: string
        It returns the url which contains the token of the kind
        https://127.0.0.1?access_token=gAAAAABc3Sh9QpE5mNx2mSz6vvvT29SAsELqkfbKQKa2977zHw3NdPBhe6jAZCBumHvYUum87j53-AzMEPXMjQw31wkRviZ1TdM5OimgTYWEEorWDmWuHnY=&user_id=FYXXXX
    """

    app_session = accessToken.SessionModel(app_id, secret_id)
    response = app_session.auth()
    # Check if we gets the response
    if response["code"] != 200:
        sys.exit()
        print('Error- Response Code != 200')
    # Get Authorization Code
    auth_code = response['data']['authorization_code']
    app_session.set_token(auth_code)
    # Get URL with the Authorization Code
    generate_token_url = app_session.generate_token()
    # Open the URL in browser
    driver.get(generate_token_url)
    # Get credentials elements from the html
    user_name = driver.find_element_by_id('fyers_id')
    password = driver.find_element_by_id('password')
    pan_card = driver.find_element_by_id('pancard')
    submit_button = driver.find_element_by_id('btn_id')
    # Fill in the credentials
    user_name.send_keys(USERNAME)
    password.send_keys(PASSWORD)
    pan_card.send_keys(PANCARD)
    submit_button.click()
    # Wait for a while so that the url changes
    time.sleep(30)
    # Get the current URL (which contains access token)
    url_with_token = driver.current_url
    driver.quit()  # Close the browser
    return url_with_token
示例#7
0
def autologin():
    global request_token
    try:
        token_path = "api_key.txt"
        key_secret = open(token_path, 'r').read().split()
        appSession = accessToken.SessionModel(key_secret[0], key_secret[1])
        response = appSession.auth()
        auth_code = response["data"]["authorization_code"]
        appSession.set_token(auth_code)
        generateTokenUrl = appSession.generate_token()
        service = webdriver.chrome.service.Service('./chromedriver.exe')
        service.start()
        options = webdriver.ChromeOptions()
        options.add_argument("--headless")
        options = options.to_capabilities()
        driver = webdriver.Remote(service.service_url, options)
        driver.get(generateTokenUrl)
        driver.implicitly_wait(10)
        username = driver.find_element_by_xpath(
            '/html/body/div/div[1]/div/form/div[1]/div/input')
        password = driver.find_element_by_xpath(
            '/html/body/div/div[1]/div/form/div[2]/div/input')
        PAN = driver.find_element_by_xpath(
            '/html/body/div/div[1]/div/form/div[4]/div/input')
        username.send_keys(key_secret[2])
        password.send_keys(key_secret[3])
        PAN.send_keys(key_secret[4])
        driver.find_element_by_xpath(
            '/html/body/div/div[1]/div/form/div[7]/button').click()
        time.sleep(30)
        request_token = driver.current_url.split('access_token=')[1].split(
            '&user_id')[0]
        with open('access_token.txt', 'w') as the_file:
            the_file.write(request_token)
        driver.quit()
    except Exception as e:
        print(e)
        driver.quit()
示例#8
0
def generate_access_token(auth_code, appId, secret_key):
    functionName = "generate_access_token"
    """
	:param auth_code: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1OTM1ODY2NzEsInN1YiI6ImF1dGhDb2RlIiwiYXBwX2lkIjoiQjhQV0xWSDhUNiIsImlzcyI6ImFwaS5sb2dpbi5meWVycy5pbiIsImF1ZCI6WyJ4OjAiLCJ4OjEiLCJ4OjIiXSwidXXXXXXXXXXXYjE3ZWU4OTQzMGRhZjA1YWUxNDI2YWVkYzI4IiwiaXBBZGRyIjoiMjIzLjIzMy40Mi40NiIsImRpc3BsYXlfbmFtZSI6IkRQMDA0MDQiLCJpYXQiOjE1OTM1ODYzNzEsIm5iZiI6MTU5MzU4NjM3MX0.IMJHzQGHQgyXt_XN0AgDrMN1keR4qolFFKO6cyXTnTg"
	:param app_id: "B8PXXXXXXX"
	:param secret_key: "XXXXXXKGN0"
	:param redirect_url: "https://XXXXXX.com"
	:return: access_token: "eyJ0eXAiOiJKV1QiLCXXXX1NiJ9.eyJpYXXXXXXXXXXMsIm5iZiI6MTU5MzU4ODM3MywiZXhwIjoxNTkzNjQ5ODEzLCJpc3MiOiJhcGkuZnllcnMuaW4iLCJzdWIiOiJhY2Nlc3MiLCJhdWQiOiJ4OjAseDoxLHg6MiIsImF0X2hhc2giOiJnQUFBQUFCZV9EcVZIZExMMTAzTVpVN1NYSkZfR2p5R3hidzMtTVVhb0VEMGI0QUVvNjFsR24tREY2OFU5cXhuNzd0UXVoOVVJalYtNm9MVXhINVFfWE1WTEJfRXpROGV2clJmUzlNUXB0Y2J5c2ltN1drWllZTT0iLCJkaXNwbGF5X25hbWUiOiJQSVlVU0ggUkFKRU5EUkEgS0FQU0UiLCJmeV9pZCI6IkRQMDA0MDQifQ.cAfrj2TxAyb8A_9DfiCb1hLIZg_mH-xvP3Ybnj3a4AE"

	1.this function takes the param and return the access_token
	2.the access_token created will be used further .(in fyersModel)]
	3. one can get the auth_code from the url generated by getauthToken function (from auth_code= ..... &user_Id=xxxxxx before &)
	"""
    # creating an instance appSession by passing app id,secret key and redirect url as parameter
    appSession = accessToken.SessionModel(client_id=appId,
                                          secret_key=secret_key,
                                          grant_type="authorization_code")

    # we need to pass the auth code in set_token method
    appSession.set_token(auth_code)
    # generate_token function will return us the access token and we store in variable "access_token"
    access_token = appSession.generate_token()
    return access_token
示例#9
0
def get_access_token( accessToken):
    app_session = accessToken.SessionModel(app_id, app_secret)
    response = app_session.auth()

    if response["code"] != 200:
        print("Fyers app login successful")

    auth_code = response["data"]["authorization_code"]
    app_session.set_token(auth_code)
    generateTokenUrl = app_session.generate_token()
    driver = webdriver.Chrome("chromedriver.exe")
    driver.get(generateTokenUrl)
    driver.find_element_by_id("fyers_id").send_keys(FYERS_ID)
    driver.find_element_by_id("password").send_keys(FYERS_PASSWORD)
    driver.find_element_by_id("pancard").send_keys(PANCARD)
    driver.find_element_by_id("btn_id").click()

    time.sleep(10)

    current_url = driver.current_url
    driver.quit()
    access_token = current_url.split("access_token=")[1]
    return access_token
def getToken(app_id, app_secret):
    """
	The variable `generateTokenUrl` will have a url like 
	https://api.fyers.in/api/v1/genrateToken?authorization_code=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqaGdqZzg3NiQ3ODVidjVANjQ3NTZ2NSZnNyM2OTg3Njc5OHhkIjoiWElHVFVYVjBSSSIsImV4cCI6MTU2MTU5NzM5Ny41NjQxNTV9.Agl-UUs63NforrUEdbG7YUlPcbFXu9hLYm4akGuIBkU&appId=Your_app_id"
	 1. This function open this url in the browser. 
	 2. This will ask you to login and will ask you to approve the app if it is not approved already.
	 3. Once that is done, it will redirect to a url (added while app creation) with the access_token. The url will look like
	    http://localhost:5000?access_token=gAAAAABc3Sh9QpE5mNx2mSz6vvvT29SAsELqkfbKQKa2977zHw3NdPBhe6jAZCBumHvYUum87j53-AzMEPXMjQw31wkRviZ1TdM5OimgTYWEEorWDmWuHnY=&user_id=FYXXXX
	 4. You have to take the access_token from the url and use that token in your going forward.
	"""
    appSession = accessToken.SessionModel(app_id, app_secret)

    response = appSession.auth()

    if response["code"] != 200:
        print response
        sys.exit()

    auth_code = response["data"]["authorization_code"]

    appSession.set_token(auth_code)

    generateTokenUrl = appSession.generate_token()
    webbrowser.open(generateTokenUrl, new=1)
示例#11
0
mydf = pd.DataFrame(columns=["Symbol", "High", "Low", "Time"])
#import stock3

#Here we generate the authorization_code to authorize the app
#In visual studio code we have to print the response to get the authorization_code
try:
    app_id = open("api_id.txt", "r").read()  #app_id is given by fyers
except IOError:
    print("api_id.txt file does not exist")

try:
    app_secret = open("app_secret.txt",
                      "r").read()  #app_secret is given by fyers
except IOError:
    print("app_secret.txt file does not exist")
app_session = accessToken.SessionModel(app_id, app_secret)
response = app_session.auth()
#print (response)    #to generate authorization_code remove #

#Now we generate the access token
#you have to generate the authorization_code after in active
#Again we comment the app_session.generate_token(), we copy the token
try:
    authorization_code = open("authorization_code.txt", "r").read()
except IOError:
    print("authorization_code.txt file does not exist")
app_session.set_token(authorization_code)
app_session.generate_token()
#print(app_session.generate_token())   #to generate token remove #

#Here we check we connected to the api or not
示例#12
0
#### Generate an authcode and then make a request to generate an accessToken (Login Flow)
"""
1. Input parameters
"""
redirect_uri = "APP REDIRECT URI"  ## redircet_uri you entered while creating APP.
client_id = "L9NY****W-100"  ## Client_id here refers to APP_ID of the created app
secret_key = "MH*****TJ5"  ## app_secret key which you got after creating the app
grant_type = "authorization_code"  ## The grant_type always has to be "authorization_code"
response_type = "code"  ## The response_type always has to be "code"
state = "sample"  ##  The state field here acts as a session manager. you will be sent with the state field after successfull generation of auth_code

### Connect to the sessionModel object here with the required input parameters
appSession = accessToken.SessionModel(client_id=client_id,
                                      redirect_uri=redirect_uri,
                                      response_type=response_type,
                                      state=state,
                                      secret_key=secret_key,
                                      grant_type=grant_type)

### Make  a request to generate_authcode object this will return a login url which you need to open in your browser from where you can get the generated auth_code
generateTokenUrl = appSession.generate_authcode()
"""There are two method to get the Login url if  you are not automating the login flow
1. Just by printing the variable name 
2. There is a library named as webbrowser which will then open the url for you without the hasel of copy pasting
both the methods are mentioned below"""
print((generateTokenUrl))
webbrowser.open(generateTokenUrl, new=1)
"""
run the code firstly upto this after you generate the auth_code comment the above code and start executing the below code """
##########################################################################################################################
示例#13
0
def request_auth():
    options = webdriver.ChromeOptions()
    options.add_argument("--headless")
    options.add_argument("--user-data-dir = chrome-data")
    options.add_experimental_option("excludeSwitches", ['enable-automation'])
    options.add_experimental_option('useAutomationExtension', False)
    driver = webdriver.Chrome(executable_path="chromdriver85/chromedriver",
                              options=options)  # , chrome_options=options)
    driver.maximize_window()

    # Authentication
    app_id = "VUJXY71KQH"
    app_secret = "Q4V3PBIKER"
    app_session = accessToken.SessionModel(app_id, app_secret)
    response = app_session.auth()

    print(response)

    # Getting authorized code into a variable
    authorization_code = response['data']['authorization_code']

    # Setting a Session
    print(app_session.set_token(authorization_code))

    access_token_url = app_session.generate_token()

    # Opening Url through Selenium
    driver.get(str(access_token_url))

    usn = driver.find_element_by_id('fyers_id')
    usn.send_keys('DJ00795')
    time.sleep(3)

    pwd = driver.find_element_by_id('password')
    pwd.send_keys('Allah@786')
    time.sleep(3)

    driver.find_element_by_class_name('login-span-pan').click()
    time.sleep(3)

    pan = driver.find_element_by_id('pancard')
    pan.send_keys('GVSPS4837L')
    time.sleep(3)

    driver.find_element_by_id('btn_id').click()

    time.sleep(5)
    wait = WebDriverWait(driver, 10)
    wait.until(EC.title_is('jainusalgotradetest.in'))
    # getting access token from browser
    exclude, redirected_url = driver.current_url.split('=', 1)
    token = redirected_url
    print(token)

    # Quiting the browser
    # driver.quit()

    # token = 'gAAAAABfeL21YprsghfV2ZcAAUQI69qwAw7C5QqCXbd1PlH9WywvAbkzIAmUctKds7XULxdefnGl_zZWmxX3XjLEGf52sPgzukOTr64OVJLe4vosXMHf788=&user_id=DJ00795'

    # By default False only
    is_async = False

    fyers = fyersModel.FyersModel(is_async)

    # accessing funds data in json
    funds_data = fyers.funds(token=token)

    avail_funds = funds_data['data']['fund_limit']
    avb = pd.json_normalize(avail_funds)
    # avb.to_csv(os.getcwd() + '/availfunds/funds.csv')

    bal = float()
    if avb.iloc[0][1] > 0:
        bal = avb.iloc[0][1]

    return fyers, token, bal