Fyers Token Automated – V3 :: Algo Trading
Fyers Token Automated – V3 :: Algo Trading
Refec this blog to understand how to automate the token generation process in Fyers API Algo trading.

Introduction

FYERS is a Zero-Brokerage stockbroking company that does not levy brokerage for investments. Through fyers, you can invest in the equities listed on all the major Indian exchanges namely NSE, BSE, & MCX.

Fyers is one of the few companies which provide stable and free APIs for algo trading and We are here to help you with your problems facing in automating any problem in your strategy development using python.

Driven by our passion for Python, we extend a helping hand to address all your concerns and obstacles. Your success is our priority.

To leverage the full potential of the FYERS API for communication, order placement, and data retrieval, a daily token generation process is required. While the semi-automatic approach persisted until version 2, FYERS has now ushered in version 3, offering a streamlined and fully automated solution to enhance your trading experience.

Requirements

  • App Creation for Client ID and Secret Key
  • Token Generation
  • Refersh Token Generation
  • Fyers Object using Token

Refernce

Breaking Down the Process

  • Create App to generate Client ID and Secret Key
  • Generate Auth Code for first time
  • Saving the access & refresh token into the file
  • Generating Daily Refresh token
  • Functions to Check token File age and genreate HashID for daily Token

Let’s Start

So, we will first go to myapi fyers and create an app.

Creating an App

Navigate here and click on Create App. You will be asked to fill the details along with name and re-direction URL and permissions.

You can give any name to your app and redirect URL could be anything and we are here taking "http://127.0.0.1:9797" and selection the permissions order placement & historical data.

Once completed all details, you will get your Client ID and Secret Key to be used.

Let’s Get the Auth Code

With these details, we need to generate the Auth Code for first time and sample python code is already give here by Fyers.

Auth Code

# Create a session model with the provided credentials
            session = fyersModel.SessionModel(
            client_id=client_id,
            secret_key=secret_key,
            redirect_uri=redirect_uri,
            response_type=response_type
            )
            # Generate the auth code using the session model
            response = session.generate_authcode()

            # Print the auth code received in the response
            print("Authenticate URL to generate the Auth Code...")
            print(response)
            print("")
            auth_code = input("Please Enter auth_code...\n")

Access & Refresh Token

Once auth code is generated, we need to generate the acess and refresh token and save it to file to be used for daily token generation. As per fyers, the refresh token is valid for 15 days and a new token every day can be generated using the same for next 15 days without any Fyers login required.

# Create a session object to handle the Fyers API authentication and token generation
            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_data = session.generate_token()

            # Print the response, which should contain the access token and other details
            print("\n Response:\n")
            # Extract access_token and refresh_token
            access_token = response_data.get("access_token", "")
            refresh_token = response_data.get("refresh_token", "")

            # Store the values in a file
            print(f"Writing the access and refrehToken.")
            with open(tokenFile, "w") as file:
                json.dump({"access_token": access_token, "refresh_token": refresh_token}, file)

            # Read the values back from the file
        
            with open(tokenFile, "r") as file:
                token_data = json.load(file)
                accessToken = token_data.get("access_token", "")
                refreshToken = token_data.get("refresh_token", "")

            print(f"Now reading the token values and refreshToken: {refreshToken}")

Daily Token

Now, we have our main Token file with access and refresh Token and now we can gereate the daily Token to be used using the refresh token for next 15 days.

print(f"Now generating the dailyToken.")
        hashid = generate_sha256_hash(client_id+secret_key)

        url = 'https://api-t1.fyers.in/api/v3/validate-refresh-token'

        headers = {
            'Content-Type': 'application/json',
            }
        print(f"Genreated hashid is {hashid}")
        data = {
            'grant_type': 'refresh_token',
            'appIdHash': hashid,
            'refresh_token': refreshToken,
            'pin': pin,
        }

        response = requests.post(url, headers=headers, json=data)

        access_token = response.json().get("access_token", "")

        # Store the values in a file
        with open(tokenDaily, "w") as file:
            json.dump({"access_token": access_token}, file)

        #    Read the values back from the file
        with open(tokenDaily, "r") as file:
            token_data = json.load(file)
            accessTokenDaily = token_data.get("access_token", "")

        print(f"Daily Token: {accessTokenDaily}")

Fyers Object

Now, we have daily token and we can generate the fyers Object which can be used to access all APIs and features offered by Fyers.

fyers = fyersModel.FyersModel(client_id=client_id, token=accessTokenDaily,is_async=False, log_path="D:\\Trading\\2023-24\\Fyers\\NIFTY_WEEKLY\\logs\\socket\\")
    # Replace the sample access token with your actual access token obtained from Fyers


    print(f"Fyers object created!!")

Other Functions

We have our main token file and daily token and now we have to arrange all in systematic manner as below:

  • First we check, if our main token file exists,
    • If yes, check if it is older than 14 days
      • If yes, delete it
      • Else, we move forward
    • If no, that means we are running the program first time and need to genrate the auth code.
  • Now, we check, if daily token file exists,
    • If yes, check if we are running today for first time
      • If we are running bewore 09:15-09:17 then it is first time, so we delete the file
      • Else, we fetch the dailyToken from the file
    • If no, that means we are running program today first time hence old token is deleted and now new daily token needs to be generated.

If we understand the above flow, we just simply use below two functions to check if main token file is older than 14 days and genreate the hashID to generate the daily token

IS FILE OLDER THEN 14 Days

def is_file_older_than_days(file_path, days):
    # Get the last modified time of the file
    last_modified_time = os.path.getmtime(file_path)

    # Calculate the current time
    current_time = time.time()

    # Calculate the time difference in seconds
    time_difference_seconds = current_time - last_modified_time

    # Calculate the time difference in days
    time_difference_days = round(float(time_difference_seconds / (24 * 3600)),2)

    print(f"[{file_path}] is {time_difference_days} days older.")

    # Check if the file is older than the specified number of days
    return time_difference_days > days

Generate HashID

def generate_sha256_hash(input_string):
    # Create a new SHA-256 hash object
    sha256_hash = hashlib.sha256()

    # Update the hash object with the bytes-like object of the input string
    sha256_hash.update(input_string.encode('utf-8'))

    # Get the hexadecimal representation of the hash
    hash_result = sha256_hash.hexdigest()

    return hash_result

Summary

Now, we have all the data and code to daily generate the new token from Refresh token for 14 days and every 14th day, we generate the main token file again.

This helps us automate entire process and we need not to generate the token daily manully or input our credentials again and again.

Complete code is as below:

from fyers_apiv3 import fyersModel
import hashlib, os
import datetime as dt
import time
import json
import requests

def generate_sha256_hash(input_string):
    # Create a new SHA-256 hash object
    sha256_hash = hashlib.sha256()

    # Update the hash object with the bytes-like object of the input string
    sha256_hash.update(input_string.encode('utf-8'))

    # Get the hexadecimal representation of the hash
    hash_result = sha256_hash.hexdigest()

    return hash_result


def is_file_older_than_days(file_path, days):
    # Get the last modified time of the file
    last_modified_time = os.path.getmtime(file_path)

    # Calculate the current time
    current_time = time.time()

    # Calculate the time difference in seconds
    time_difference_seconds = current_time - last_modified_time

    # Calculate the time difference in days
    time_difference_days = round(float(time_difference_seconds / (24 * 3600)),2)

    print(f"[{file_path}] is {time_difference_days} days older.")

    # Check if the file is older than the specified number of days
    return time_difference_days > days
    
def fyerObj(client_id,secret_key,pin):    
    
    redirect_uri = "https://127.0.0.1:9696/"
    response_type = "code"  
    state = "sample_state"
    response_type = "code" 
    grant_type = "authorization_code"  

    tokenFile = "D:\\Trading\\2023-24\\Fyers\\Extra\\token\\token.json"
    tokenDaily = "D:\\Trading\\2023-24\\Fyers\\Extra\\token\\tokenDaily.json"

    current_time = dt.datetime.now()
    if current_time.hour < 9 or (current_time.hour == 9 and current_time.minute < 17):
        print(f"Removing tokenDaily file as new day and new session!!")
        if os.path.exists(tokenDaily):
            os.remove(tokenDaily)
        else:
            print(f"tokenDaily file does not exist to delete.")

    days_threshold = 14
    if os.path.exists(tokenFile):
        if is_file_older_than_days(tokenFile, days_threshold):
            print(f"The file '[{tokenFile}]' is older than {days_threshold} days.")
            print(f"Removing Token File...")
            os.remove(tokenFile)
        else:
            print(f"The file '[{tokenFile}]' is not older than {days_threshold} days.")

    if os.path.exists(tokenDaily):
        print(f"Daily token file exists.")
         #Read the values back from the file
        with open(tokenDaily, "r") as file:
            token_data = json.load(file)
            accessTokenDaily = token_data.get("access_token", "")
            
        print(f"Daily Token: {accessTokenDaily}")

    else:

        if os.path.exists(tokenFile):
            print(f"token File exist!!")
            # Read the values back from the file
            with open(tokenFile, "r") as file:
                token_data = json.load(file)
                accessToken = token_data.get("access_token", "")
                refreshToken = token_data.get("refresh_token", "")
            print(f"Refresh Token: {refreshToken}")
        else:
            print("\n\n\n")
            print(f"Token file do not exist hence generating new one...")
            # Create a session model with the provided credentials
            session = fyersModel.SessionModel(
            client_id=client_id,
            secret_key=secret_key,
            redirect_uri=redirect_uri,
            response_type=response_type
            )
            # Generate the auth code using the session model
            response = session.generate_authcode()

            # Print the auth code received in the response
            print("Authenticate URL to generate the Auth Code...")
            print(response)
            print("")
            auth_code = input("Please Enter auth_code...\n")
            # Create a session object to handle the Fyers API authentication and token generation
            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_data = session.generate_token()

            # Print the response, which should contain the access token and other details
            print("\n Response:\n")
            # Extract access_token and refresh_token
            access_token = response_data.get("access_token", "")
            refresh_token = response_data.get("refresh_token", "")

            # Store the values in a file
            print(f"Writing the access and refrehToken.")
            with open(tokenFile, "w") as file:
                json.dump({"access_token": access_token, "refresh_token": refresh_token}, file)

            # Read the values back from the file
        
            with open(tokenFile, "r") as file:
                token_data = json.load(file)
                accessToken = token_data.get("access_token", "")
                refreshToken = token_data.get("refresh_token", "")

            print(f"Now reading the token values and refreshToken: {refreshToken}")

        action = input("Enter to continue")
        print(f"Now generating the dailyToken.")
        hashid = generate_sha256_hash(client_id+secret_key)

        url = 'https://api-t1.fyers.in/api/v3/validate-refresh-token'

        headers = {
            'Content-Type': 'application/json',
            }
        print(f"Genreated hashid is {hashid}")
        data = {
            'grant_type': 'refresh_token',
            'appIdHash': hashid,
            'refresh_token': refreshToken,
            'pin': pin,
        }

        response = requests.post(url, headers=headers, json=data)

        access_token = response.json().get("access_token", "")

        # Store the values in a file
        with open(tokenDaily, "w") as file:
            json.dump({"access_token": access_token}, file)

        #    Read the values back from the file
        with open(tokenDaily, "r") as file:
            token_data = json.load(file)
            accessTokenDaily = token_data.get("access_token", "")

        print(f"Daily Token: {accessTokenDaily}")


    fyers = fyersModel.FyersModel(client_id=client_id,         token=accessTokenDaily,is_async=False, log_path="")
    # Replace the sample access token with your actual access token obtained from Fyers


    print(f"Fyers object created!!")
    return fyers

client_id = "************"
secret_key = "************"
pin = "*****"

fyersOb = fyerObj(client_id,secret_key,pin)

data = {
    "symbol":"NSE:SBIN-EQ",
    "resolution":"D",
    "date_format":"0",
    "range_from":"1690895316",
    "range_to":"1691068173",
    "cont_flag":"1"
}

response = fyersOb.history(data=data)
print(response)

Not Satisfied, follow us on YouTube for complete walkthrough

1 thought on “Fyers Token Automated – V3 :: Algo Trading”

Leave a Comment