Introduction to Fyers API

Home » Python » Fyers API » Introduction to Fyers API

Table of Contents

API Fyers
Fyers API

Understanding the program

You might be a trader, a typical trading is done via a trading application or their website. But you might also know that their is also one more way to trade, which is via programs, the programs which is self made by yourself or your’s trusted.

Know more about Fyers API here.

We have done trading via the application and the website, it was good at the initial phases of our training as a beginner trader, but as we progressed, we found that there are some limitations to the application or the website which you are using.

Some limitations might include: Alerting, highlight, Logs, Viewing multiple stocks concurrently.

You might have found your own limitations while using the given programs. So, what can be done?, you might have this question and the answer can be as simple as make your own program or use the one which is made by yours trusted.

Our goal here is inspire and provide information, and we hope you find them useful. Ultimately, it is upto you to decide how you want to engage with them and whether they might fit into your own projects.

Let’s get started:)

Project 1: Login into the fyers API

We have decided that it will be easy to undestand the content if we provide it in the projects format. We will provide the code usage, the code itself and its functions.

First is the login phase, the API needs the authentication, it needs to know you are you and not someone who is pretending to be yourself. 

The API will need the following info to authenticate you.

1 Cliend ID 

2 Secret Key

3 Fyers ID

4 TOTP key

5 PIN

You can find the Fyers ID during the login screen, ex.XA00001,and you also know your PIN.

You can find the TOTP key in the fyers settings. For the Client ID and Secret key, you will need to login to the Fyers API with your account, After login, you can create an app, the app will have the App ID which is Client ID and Secret ID which is the Secret Key.

After getting all the needed data, you can put them into the program below.


#This file is used for Login
#It depends on credential

from pyotp import totp
from fyers_apiv3 import fyersModel
import webbrowser 
from selenium import webdriver
#from webdriver_manager.chrome import ChromeDriverManager
#from selenium.webdriver.chrome.service import Service
import time
from datetime import datetime, timedelta, date
from  time import sleep
import os
import pyotp
import requests
import json
import math
import pytz
from urllib.parse import parse_qs,urlparse
import warnings
import pandas as pd


#Variables

redirect_uri = "https://www.google.com"
client_id=''
secret_key = ''
FY_ID = ""  # Your fyers ID
TOTP_KEY = ""  # TOTP secret is generated when we enable 2Factor TOTP from myaccount portal
PIN = ""  # User pin for fyers account

## 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 = fyersModel.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()
generateTokenUrl


pd.set_option('display.max_columns', None)
warnings.filterwarnings('ignore')

import base64
def getEncodedString(string):
string = str(string)
base64_bytes = base64.b64encode(string.encode("ascii"))
return base64_bytes.decode("ascii")


URL_SEND_LOGIN_OTP="https://api-t2.fyers.in/vagator/v2/send_login_otp_v2"
res = requests.post(url=URL_SEND_LOGIN_OTP, json={"fy_id":getEncodedString(FY_ID),"app_id":"2"}).json()   
print(res) 


if datetime.now().second % 30 > 27 : sleep(5)
URL_VERIFY_OTP="https://api-t2.fyers.in/vagator/v2/verify_otp"
res2 = requests.post(url=URL_VERIFY_OTP, json= {"request_key":res["request_key"],"otp":pyotp.TOTP(TOTP_KEY).now()}).json()  
print(res2) 


ses = requests.Session()
URL_VERIFY_OTP2="https://api-t2.fyers.in/vagator/v2/verify_pin_v2"
payload2 = {"request_key": res2["request_key"],"identity_type":"pin","identifier":getEncodedString(PIN)}
res3 = ses.post(url=URL_VERIFY_OTP2, json= payload2).json()  
print(res3) 

ses.headers.update({
'authorization': f"Bearer {res3['data']['access_token']}"
})


TOKENURL="https://api-t1.fyers.in/api/v3/token"
payload3 = {"fyers_id":FY_ID,
     "app_id":client_id[:-4],
     "redirect_uri":redirect_uri,
     "appType":"100","code_challenge":"",
     "state":"None","scope":"","nonce":"","response_type":"code","create_cookie":True}

res3 = ses.post(url=TOKENURL, json= payload3).json()  
print(res3)


url = res3['Url']
print(url)
parsed = urlparse(url)
auth_code = parse_qs(parsed.query)['auth_code'][0]
auth_code


grant_type = "authorization_code" 

response_type = "code"  

session = fyersModel.SessionModel(
client_id=client_id,
secret_key=secret_key, 
redirect_uri=redirect_uri, 
response_type=response_type, 
grant_type=grant_type
)



# Set the authorization code in the session object
session.set_token(auth_code)

# Generate the access token using the authorization code
response = session.generate_token()

# Print the response, which should contain the access token and other details
#print(response)


access_token = response['access_token']

# Initialize the FyersModel instance with your client_id, access_token, and enable async mode
fyers = fyersModel.FyersModel(client_id=client_id, is_async=False, token=access_token, log_path=os.getcwd())


# In[ ]:


#print(fyers.get_profile())
a = open("access.txt",'w')
a.write(access_token)
a.close()
print('Hello')
print(access_token)


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *