can any one share API V2 Python Authorization code and token generation code together

can any one share API V2 Python Authorization code and token generation code together.

The V2 Doc is very confusing and not given complete information.

Please help

My Code is

from fyers_api import fyersModel
from fyers_api import accessToken

client_id = open(‘app_id2.txt’,‘r’).read()
secret_key = open(‘app_secret2.txt’,‘r’).read()
redirect_uri=https://trade.fyers.in/api-login/redirect-uri/index.html

session=accessToken.SessionModel(client_id=client_id,secret_key=secret_key,redirect_uri=redirect_uri,response_type=‘code’,grant_type=None,state=None,scope=None,nonce=None)
response = session.generate_authcode()
#print(response)

auth_code = open(‘auth_code.txt’,‘r’).read()

session.set_token(auth_code)
response = session.generate_token()
print(response)
access_token = response[“access_token”]

Same, I am also facing the same trouble.
The login documentation is very confusing.

Hello,

You can try below code, it worked for me.

This can do automated login to Fyers API2

import time
from urllib.parse import urlparse, parse_qs
import requests
from fyers_api import fyersModel
from fyers_api import accessToken
import traceback
import json

# FILL YOU DETAILS IN BELOW **HIGHLIGHTED** FIELDS

client_id = "**YOURID**"
secret_key = "**YOURKEY**"
redirect_uri = "**YOUR_REDIRECT_URL**"
response_type = "code"
grant_type = "authorization_code"
state = "private"
nonce = "private"

input = {"fyers_id": "**YOURID**", "password": "**YOUR_PASSWORD**", "pan_dob": "**YOUR_PAN**", "app_id": "**YOUR_APP_ID**",
"redirect_uri": "**YOUR_REDIRECT_URL**", "appType": "100", "code_challenge": "", "state": "private",
"scope": "", "nonce": "private", "response_type": "code", "create_cookie": "true"}

try:
session = accessToken.SessionModel(client_id=client_id, secret_key=secret_key, redirect_uri=redirect_uri, response_type=response_type, grant_type=grant_type, state=state, nonce=nonce)
response = session.generate_authcode()
print("Response from Try-Catch 1 is - \n", response)

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": response
}

result = [requests.post](http://requests.post)("[https://api.fyers.in/api/v2/token](https://api.fyers.in/api/v2/token)",
headers=headers, json=input, allow_redirects=True)
var = json.loads(result.content)
URL = var["Url"]
print(URL)
parsed = urlparse(URL)
parsedlist = parse_qs(parsed.query)['auth_code']
auth_code = parsedlist[0]
session.set_token(auth_code)
response = session.generate_token()

access_token = response["access_token"]

**#INSERT YOUR DESKTOP PATH FOR LOG FILE CREATION**
fyers = fyersModel.FyersModel(client_id=client_id, token=access_token, log_path="**/Users/username/Desktop**")

is_async = True

**#SAMPLE ORDER PLACEMENT CODE WRITTEN BELOW !!!!**

data = {
"symbol": "NSE:SBIN-EQ",
"qty": 1,
"type": 1,
"side": 1,
"productType": "MARGIN",
"limitPrice": 500,
"stopPrice": 0,
"validity": "DAY",
"disclosedQty": 0,
"offlineOrder": "False",
"stopLoss": 5,
"takeProfit": 8
}

print([fyers.place](http://fyers.place)_order(data))

except:
print(traceback.print_exc())

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

this error is showing up in

session = accessToken.SessionModel(client_id=client_id, secret_key=secret_key, redirect_uri=redirect_uri, response_type=response_type, grant_type=grant_type, state=state, nonce=nonce)

can anyone pls help?

Have you done “pip install fyers-apiv2” ??

thanks for the reply bro… i did it that way but the files i got was corrupt.. i had to download the latest files maually from pipy and then paste is to libraries directory

Hello Vishnu,

it is still not wokring for me.

Any other solutions ?

thanks

Hello Jijoy,

I’m newbie to python.

Can you please explain in detail?

Please add screenshots if possible.

Thanks.

Hi,

Please ping me on personal chat or email me at [email protected] and let’s work something out.

Everyone including myself facing error

TypeError: init() got an unexpected keyword argument ‘client_id’ at “accessToken.SessionModel”

What is really missing? Can somebody help here?

i am getting this error when i run this program

line 39, in

URL = var[“Url”]

KeyError: ‘Url’

None

I am also facing the same error

Do this, this works for me

pip uninstall fyers-api

pip uninstall fyers-apiv2

pip install fyers-apiv2

The mentioned code is for Fyers API Version 2. Make sure you have fyers-apiv2 python package installed.

Somehow found it how to get access token after a long fight.

Try Github sample code is there in FyersDev

Thanks, Pranav for sharing the code. This works with the following changes

f**rom **urllib.parse **import **urlparse, parse_qs
**import **requests
**from **fyers_api **import **fyersModel
**from **fyers_api **import **accessToken
**import **traceback
**import **json

*# FILL YOU DETAILS IN BELOW HIGHLIGHTED FIELDS*

client_id = **""**
secret_key = **""**
redirect_uri = **"[http://localhost:8080](http://localhost:8080)"**
response_type = **"code"**
grant_type = **"authorization_code"**
state = **"None"**
nonce = **"private"**

input = {**"fyers_id"**:**""**,**"password"**:**""**,**"pan_dob"**:**""**,**"app_id"**:**""**,**"redirect_uri"**:**"[http://localhost:8080](http://localhost:8080)"**,**"appType"**:**"100"**,**"code_challenge"**:**""**,**"state"**:**"None"**,**"scope"**:**""**,**"nonce"**:**""**,**"response_type"**:**"code"**,**"create_cookie"**:**True**}

session = session=accessToken.SessionModel(client_id=client_id,
secret_key=**''**,redirect_uri=**'[http://localhost:8080](http://localhost:8080)'**,
response_type=**'code'**, grant_type=**'authorization_code'**,state= **None **)
response = session.generate_authcode()
print(**"Response from Try-Catch 1 is - \n"**, response)

headers = {
**"accept"**: **"*/*"**,
**"accept-language"**: **"en-IN,en-US;q=0.9,en;q=0.8"**,
**"content-type"**: **"application/json; charset=UTF-8"**,
**"sec-ch-ua" **:**'"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"'**,
**"User-Agent"**: **"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"**,
}

result = [requests.post](http://requests.post)(**"[https://api.fyers.in/api/v2/token](https://api.fyers.in/api/v2/token)"**,
headers=headers, json=input, allow_redirects=**True**)
var = json.loads(result.content)
URL = var[**"Url"**]
print(URL)
parsed = urlparse(URL)
parsedlist = parse_qs(parsed.query)[**'auth_code'**]
auth_code = parsedlist[0]
session.set_token(auth_code)
response = session.generate_token()
access_token = response[**"access_token"**]
print(access_token)

fyers = fyersModel.FyersModel(client_id=client_id, token=access_token,log_path=**"/Users/dedula/code/pycharmprojects/stocks/daydata"**)

print(fyers.get_profile())

data = {**"symbol"**:**"NSE:SBIN-EQ"**,**"resolution"**:**"1"**,**"date_format"**:**"0"**,**"range_from"**:**"1629695667"**,**"range_to"**:**"1629710067"**,**"cont_flag"**:**"1"**}

print(fyers.history(data))

print(fyers.orderbook())

This is the final working code.. Thank you Pranav for giving the right direction

f**rom **urllib.parse **import **urlparse, parse_qs
**import **requests
**from **fyers_api **import **fyersModel
**from **fyers_api **import **accessToken
**import **traceback
**import **json

*# FILL YOU DETAILS IN BELOW HIGHLIGHTED FIELDS*

client_id = **""**
secret_key = **""**
redirect_uri = **"****http://localhost:8080****"**
response_type = **"code"**
grant_type = **"authorization_code"**
state = **"None"**
nonce = **"private"**

input = {**"fyers_id"**:**""**,**"password"**:**""**,**"pan_dob"**:**""**,**"app_id"**:**""**,**"redirect_uri"**:**"****http://localhost:8080****"**,**"appType"**:**"100"**,**"code_challenge"**:**""**,**"state"**:**"None"**,**"scope"**:**""**,**"nonce"**:**""**,**"response_type"**:**"code"**,**"create_cookie"**:**True**}

session = session=accessToken.SessionModel(client_id=client_id,
secret_key=**''**,redirect_uri=**'****http://localhost:8080****'**,
response_type=**'code'**, grant_type=**'authorization_code'**,state= **None **)
response = session.generate_authcode()
print(**"Response from Try-Catch 1 is - \n"**, response)

headers = {
**"accept"**: **"*/*"**,
**"accept-language"**: **"en-IN,en-US;q=0.9,en;q=0.8"**,
**"content-type"**: **"application/json; charset=UTF-8"**,
**"sec-ch-ua" **:**'"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"'**,
**"User-Agent"**: **"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"**,
}

result = requests.post(**"****https://api.fyers.in/api/v2/token****"**,
headers=headers, json=input, allow_redirects=**True**)
var = json.loads(result.content)
URL = var[**"Url"**]
print(URL)
parsed = urlparse(URL)
parsedlist = parse_qs(parsed.query)[**'auth_code'**]
auth_code = parsedlist[0]
session.set_token(auth_code)
response = session.generate_token()
access_token = response[**"access_token"**]
print(access_token)

fyers = fyersModel.FyersModel(client_id=client_id, token=access_token,log_path=**"/Users/dedula/code/pycharmprojects/stocks/daydata"**)

print(fyers.get_profile())

data = {**"symbol"**:**"NSE:SBIN-EQ"**,**"resolution"**:**"1"**,**"date_format"**:**"0"**,**"range_from"**:**"1629695667"**,**"range_to"**:**"1629710067"**,**"cont_flag"**:**"1"**}

print(fyers.history(data))

print(fyers.orderbook())

I have been getting the var[“url”] error. I think the error is somewhere in retrieving the auth_code using urllib and requests. When debugged, i get the error “Please enter valid appId” or “Please pass Sha256 hash values of appId and secretId”. So, i tried writing the code using Selenium WebDriver. Check it out:

import time
import pandas as pd

from fyers_api import fyersModel
from fyers_api import accessToken
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

client_id = “<–Your AppID–>”
secret_key = “<–Your SecretKey–>”
redirect_uri = “<–Your RedirectURI–>”
response_type = “code”
grant_type = “authorization_code”
state = “None”
nonce = “private”
log_path = r’<–Your LogPath–>\fyers\Logs’
is_async = True

def getAuthCode(session):

response = session.generate_authcode()
print(response)

options = Options()
#options.headless = True     <--IF Your Want Selenium to work without opening a browser window, uncomment this-->
browser = webdriver.Firefox(options=options)
browser.get(response)

if(browser.current_url == **'[https://api.fyers.in/api/v2/generate-authcode?client_id=](https://api.fyers.in/api/v2/generate-authcode?client_id=)'**+client_id+**'&redirect_uri=https%3A%2F%[2Ftrade.fyers.in](http://2Ftrade.fyers.in)%2Fapi-login%2Fredirect-uri%2Findex.html&response_type=code&state=None&nonce=private'**):
    browser.find_element_by_xpath(**'/html/body/div/div[1]/div/form/div[1]/div/input'**).send_keys(**'<--Your FyersWeb LoginID-->'**)
    browser.find_element_by_xpath(**'//*[@id="password"]'**).send_keys(**'<--YourFyersWebPassword-->'**)
    browser.find_element_by_xpath(**'/html/body/div/div[1]/div/form/div[4]/div/input'**).send_keys(**'<--Your PAN-->'**)
    browser.find_element_by_xpath(**'/html/body/div/div[1]/div/form/div[7]/button'**).click()
    time.sleep(1)

url = browser.current_url

start = **'auth_code='**

** **end = ‘&state=None’
** **ind = url.find(start)
authcode = url[ind + len(start):-len(end)] #Separating the authcode from Fyers API redirected site

print(**"auth ="**+ auth_code)
return auth_code

def getAccessToken(session):
response = session.generate_token()
access_token = response[“access_token”]
return access_token

if name == main:
session=accessToken.SessionModel(client_id=client_id,secret_key=secret_key,redirect_uri=redirect_uri,response_type=response_type, grant_type=grant_type,state=state,nonce=nonce)
auth_code = getAuthCode(session)
session.set_token(auth_code)
access_token = getAccessToken(session)
fyers = fyersModel.FyersModel(client_id=client_id, token=access_token, log_path=log_path)
fyers.token = access_token
# print(fyers.get_profile())

  • print(fyers.tradebook())*

  • print(fyers.positions())*

  • print(fyers.holdings())*

    data = {“symbols” :“NSE:NIFTYBANK-INDEX”}
    sym = fyers.quotes(data)
    print(sym[‘d’][0][‘v’][‘cmd’])
    print(d)

Please Help me

fyers = fyersModel.FyersModel(client_id=client_id, token=access_token,log_path=" ")

what is define in fyersModel file?

what is define in inpath which path?

what is define this file, please

Thanks ganesh your code is working fine (with some changes).

This v2 api is a disaster, the official code never works and is absolute dog excrement.