Automated login to Fyers API

#Automatic login to fyers API
app_id = "Insert your API ID"
app_secret = "Insert your API secret"
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()

driver = [webdriver.Chrome](http://webdriver.Chrome)("Insert the path to chrome driver")
driver.get(url)

time.sleep(5)
driver.find_element_by_xpath('//*[@id="fyers_id"]').send_keys("Insert your Client ID")
driver.find_element_by_xpath('//*[@id="password"]').send_keys("Insert your Password")
driver.find_element_by_xpath('//*[@id="pancard"]').send_keys("Insert your PAN number")
driver.find_element_by_xpath('//*[@id="btn_id"]').click()

time.sleep(10)
token=driver.current_url[36:]
is_async = False #(By default False, Change to True for asnyc API calls.)
fyers = fyersModel.FyersModel(is_async)
driver.quit()

I use this code for an automated login using python. It primarily uses selenium to do the work. Does anyone have a better methodology?

I hope this authentication module will help you.

**def request_auth():**

** driver = [webdriver.Chrome](http://webdriver.Chrome)(executable_path="chromdriver85/chromedriver",**
** options=options)**

** # Authentication**
** app_id = "XXXXXXXXX"**
** app_secret = "XXXXXXXXX"**
** app_session = accessToken.SessionModel(app_id, app_secret)**
** response = app_session.auth()**

** # 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('User ID')**
** time.sleep(3)**

** pwd = driver.find_element_by_id('password')**
** pwd.send_keys('Password')**
** 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('PANCARD')**
** time.sleep(3)**

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

** WebDriverWait(driver,20).until(EC.title_contains('app website nam'))**
** # getting access token from browser**
** exclude, redirected_url = driver.current_url.split('=', 1)**
** token = redirected_url**
** print(token)**
** **

** # Quiting the browser**
** driver.quit()**

** **
** # By default False only**
** is_async = False**

** # fyers**
** fyers = fyersModel.FyersModel(is_async)**

** return fyers, token**

Thanks @bg6u8dOikZ but this pretty much does the same thing the same way.

There are simple ways I guess.

import sys
import requests
import csv
import re
import json

from fyers_api import fyersModel, accessToken
# NOTE Install fyers_api => python -m pip install fyers_api

def get_token(app_id, app_secret, fyers_id, password, pan_dob):
    appSession = accessToken.SessionModel(app_id, app_secret)
    response = appSession.auth()
    if response["code"] != 200:
        return response
        # sys.exit()

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

    appSession.set_token(auth_code)

    generateTokenUrl = appSession.generate_token()
    # [webbrowser.open](http://webbrowser.open)(generateTokenUrl, new=1)
    headers = {
        "accept": "*/*",
        "accept-language": "en-IN,en-US;q=0.9,en;q=0.8",
        "content-type": "application/json; charset=UTF-8",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "referrer": generateTokenUrl
    }
    payload = {"fyers_id": fyers_id, "password": password,
               "pan_dob": pan_dob, "appId": app_id, "create_cookie": False}
    result = [requests.post](http://requests.post)("[https://api.fyers.in/api/v1/token](https://api.fyers.in/api/v1/token)",
                           headers=headers, json=payload, allow_redirects=True)
    if result.status_code != 200:
        print('error occurred status code :: ', result.status_code)
        return
    print(result.json())
    result_url = result.json()["Url"]
    token_re = [re.search](http://re.search)(r'access_token=(.*?)&', result_url, re.I)
    if token_re:
        return token_[re.group](http://re.group)(1)
    return "error"

def main():
    # access_token from the redirect url
    user = json.loads(open('userinfo.json', 'r').read().strip())
    # NOTE Contents of userinfo.json
    # {
    #     "app_id": "",
    #     "app_secret": "",
    #     "fyers_id": "",
    #     "password": "",
    #     "pan_or_dob": ""
    # }

    access_token = get_token(app_id=user['app_id'], app_secret=user['app_secret'],
                             fyers_id=user['fyers_id'], password=user['password'], pan_dob=user['pan_or_dob'])
    with open('access_token.txt', 'w') as wr1:
        wr = csv.writer(wr1)
        wr.writerow([access_token])

if __name__ == '__main__':
    main()

Once you store token in txt file, you can use it later.

import json
import pandas as pd

from fyers_api import fyersModel
# NOTE Install fyers_api => python -m pip install fyers_api

fyers = None

def main():
    global fyers
    access_token = open('access_token.txt', 'r').read().strip()
    # is_async = False #(By default False, Change to True for asnyc API calls.)
    fyers = fyersModel.FyersModel()
    print(fyers.get_profile(token=access_token))

    print(fyers.tradebook(token=access_token))
    data = fyers.orders(token=access_token)
    order_book = data['data']['orderBook']

    df = pd.DataFrame(order_book)
    print(df)
    print(df.columns)

if __name__ == '__main__':
    main()

Has anybody done this on API version 2? I am looking for a solution on the requests.post method. What would be the URL for V2?

headers = { “accept”: “/”, “accept-language”: “en-IN,en-US;q=0.9,en;q=0.8”, “content-type”: “application/json; charset=UTF-8”, “sec-fetch-dest”: “empty”, “sec-fetch-mode”: “cors”, “sec-fetch-site”: “same-origin”, “referrer”: generateTokenUrl }

payload = {“fyers_id”: fyers_id, “password”: password, “pan_dob”: pan_dob, “appId”: app_id, “create_cookie”: False}

result = requests.post(“https://api.fyers.in/api/v1/token”, headers=headers, json=payload, allow_redirects=True)

Any other changes? I am able to do with the chrome driver, but it will be dependent on chrome which i am not so keen.

Hi Meenakshi,

I have this figured out. Kindly send me a mail to [email protected]

Can you help me too I am using rest but if you provide python headers ,referer and payload/body It too would make my day for V2

The. Documentation is quite confusing but I know one we get handy it won’t be.I just need referer , body and payloads for the auth code and token

For automating the process of getting access token using python (with & without the use of selenium webdriver), Please refer to this: https://github.com/tkanhe/Fyers-API-Access-Token-Generation-V2

I got it already just about some day back but thanks a lot I know how importance and difficult it is for a developer to get the code .

Really appreciate you efforts

facing problem with new login flow, while using send keys to pin input box it returns “Message: element not interactable”

You can try this code following code it worked for me:

Hi @WH9N49RaFa,

We’re not supporting automation of user login flows due to security purposes. Saving a broking account username and password in plain text in code or on a (third-party) database exposes the user’s security.

Kindly follow the supported approach for validation as provided in the link- https://github.com/FyersDev/fyers-api-sample-code/blob/sample_v2/My%20API%20Sample%20Script(GET%20STARTED)/Sample_Test_trading_Data.py
Let us know if you need further help.

Thanks!

What if I have to do this to 10 of my clients, by the way. I am Fyers Sub broker, in the last 3 months you guys have made changes several times.. instead of focusing on trading I have ended up coding for all of Fyers sins. now the recent one is pin based authentication.. clearly show immaturity and why your API is free.. let alone adding value to Fyers API users the pain is immense to keep up… I coded for v1, last week ended up coding for v2 and now refactor for PIN based .. complete pain as hell.

Does this works for PIN based Authentication .. if not it is of no use for auto login.

Hi Ravi

have you got any clue that how to automate PIN based login?

The below code considers v1,v2 and the recent PIN based… should work..

import os

import sys

import requests

import time

from urllib.parse import urlparse, parse_qs

from fyers_api import fyersModel

from fyers_api import accessToken

import environment as env

import pandas as pd

from sqlalchemy import create_engine

from urllib import parse

import environment as env

client_id=‘app_id’

app_id = client_id[:-4]

secret_key=‘app_secret’

username=‘client_id’

password=‘password’

pan=‘pancard’

pin=int(‘pin’)

redirect_uri=“http://127.0.0.1/loginstatus”

session = accessToken.SessionModel(client_id=client_id, secret_key=secret_key, redirect_uri=redirect_uri,

                                  response_type='code', grant_type='authorization_code')

s = requests.Session()

data1 = f’{{“fy_id”:“{username}”,“password”:“{password}”,“app_id”:“2”,“imei”:“”,“recaptcha_token”:“”}}’

r1 = s.post(‘https://api.fyers.in/vagator/v1/login’, data=data1)

request_key = r1.json()[“request_key”]

data2 = f’{{“request_key”:“{request_key}”,“identity_type”:“pin”,“identifier”:“{pin}”,“recaptcha_token”:“”}}’

r2 = s.post(‘https://api.fyers.in/vagator/v1/verify_pin’, data=data2)

headers = {

   'authorization': f"Bearer {r2.json()['data']['access_token']}",

   'content-type': 'application/json; charset=UTF-8'

}

data3 = f’{{“fyers_id”:“{username}”,“app_id”:“{app_id}”,“redirect_uri”:“{redirect_uri}”,“appType”:“100”,“code_challenge”:“”,“state”:“abcdefg”,“scope”:“”,“nonce”:“”,“response_type”:“code”,“create_cookie”:true}}’

r3 = s.post(‘https://api.fyers.in/api/v2/token’, headers=headers, data=data3)

parsed = urlparse(r3.json()[‘Url’])

auth_code = parse_qs(parsed.query)[‘auth_code’][0]

session.set_token(auth_code)

response = session.generate_token()

token = response[“access_token”]

print(token)

print(‘Got the access token!!!’)

try:

   with open("access_token.csv", "a") as fyers_token:

       fyers_token.write(str(client_id)+","+str(token))

       print("Wrote ---->",str(client_id)+","+str(token))

       fyers_token.write("\n")

       fyers_token.close()

   print("Access token generated successfully")

except:

   print("Some went wrong Credentials or Network Connetivity")

Worked smoothly, Thanks

Getting below error

Traceback (most recent call last):

File “D:/Fyer_Pract/Fyers_AutoLogin.py”, line 51, in

access_token = get_token()

File “D:/Fyer_Pract/Fyers_AutoLogin.py”, line 25, in get_token

grant_type=“authorization_code”)

TypeError: init() got an unexpected keyword argument ‘client_id’

Try https://github.com/tkanhe/Fyers-API-Access-Token-Generation-V2. Its working fine.