How do i automate the login process? i need to provide the authcode again and again
from fyers_apiv3 import fyersModel
import webbrowser
import plotly.graph_objs as go
from stocktrends import Renko
import plotly.io as pio
import numpy as np
#pio.renderers.default = ‘svg’
pio.renderers.default = ‘browser’
from plotly.subplots import make_subplots
import copy
import statsmodels.api as sm
import pandas as pd
import strategy #import strategy
import datetime
“”"
- Input parameters
“”"
redirect_uri= “” ## redircet_uri you entered while creating APP.
client_id = “” ## Client_id here refers to APP_ID of the created app
secret_key = “” ## app_secret key which you got after creating the app
grant_type = “” ## 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
Generate an authcode and then make a request to generate an accessToken (Login Flow)
def generate_appSession():
### 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()
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 """
##########################################################################################################################
return appSession
def connect_Fyers(appSession,auth_code):
### After succesfull login the user can copy the generated auth_code over here and make the request to generate the accessToken
appSession.set_token(auth_code)
response = appSession.generate_token()
## There can be two cases over here you can successfully get the acccessToken over the request or you might get some error over here. so to avoid that have this in try except block
try:
access_token = response["access_token"]
except Exception as e:
print(e,response) ## This will help you in debugging then and there itself like what was the error and also you would be able to see the value you got in response variable. instead of getting key_error for unsuccessfull response.
## Once you have generated accessToken now we can call multiple trading related or data related apis after that in order to do so we need to first initialize the fyerModel object with all the requried params.
"""
fyerModel object takes following values as arguments
1. accessToken : this is the one which you received from above
2. client_id : this is basically the app_id for the particular app you logged into
"""
fyers = fyersModel.FyersModel(token=access_token,is_async=False,client_id=client_id,log_path="")
return fyers
app_session=generate_appSession()
After this point you can call the relevant apis and get started with
auth_code = “”
####################################################################################################################
“”"
- User Apis : This includes (Profile,Funds,Holdings)
“”"
fyers=connect_Fyers(app_session,auth_code)
#ready to backtest
#NS:SMSPHARMA-EQ
brick_size=“”
start_date=“2024-08-20”
end_date=“2024-09-13”
interval_taken=“15”
tickers=[“NSE:SMSPHARMA-EQ”]
ohlcv_data={}
def get_historicalData(ticker):
symbol = ticker # Fyers format: NSE:<stock>
resolution = interval_taken # D for daily, or "5" for 5 minutes, "1" for 1 minute, etc.
date_format = 1 # 1 for YYYY-MM-DD format
range_from = start_date # Start date in YYYY-MM-DD format
#range_to = str(datetime.date.today()) # End date (current day)
range_to = end_date # End date (current day)
historical_data_params = {
"symbol": symbol,
"resolution": resolution,
"date_format": date_format,
"range_from": range_from,
"range_to": range_to,
"cont_flag": "1" # Continuous data flag, used for futures contracts. 0 for no, 1 for yes.
}
response = fyers.history(data=historical_data_params) #historical data recvd
candles = response["candles"] #contains timestamp,open,high,low,close and volume
df = pd.DataFrame(candles, columns=["date", "open", "high", "low", "close", "volume"])
df["date"] = pd.to_datetime(df["date"], unit='s')
return df
#fetching historical data
for ticker in tickers:
ohlcv_data[ticker]=get_historicalData(ticker) #returns a modified df as per my requirements