Fyers API Live Data Access: Program Guide

Home » Python » Fyers API » Fyers API Live Data Access: Program Guide

Table of Contents

Fyers API Live Data Access
A desktop terminal

Introduction to Fyers API Live Data

Now that we’ve explored how to access various data related to our profile and funds, Accordingly, we will focus on how to retrieve live market data using Fyers API live data access.

We will explore how to acquire data for one or more symbols, with updates every second. Furthermore, we will learn how to utilize this real-time market data.

In this post, we will demonstrate how to gather real-time market data for one or more symbols at one-second intervals. Therefore, we will be able to track market trends and make informed investment decisions.


from fyers_apiv3.FyersWebsocket import data_ws


with open('access.txt', 'r') as a:
    access_token = a.read()
client_id = 'your client id'

def onmessage(message):
    print("Response:", message)

def onerror(message):
    """
    Callback function to handle WebSocket errors.

    Parameters:
        message (dict): The error message received from the WebSocket.


    """
    print("Error:", message)


def onclose(message):
    """
    Callback function to handle WebSocket connection close events.
    """
    print("Connection closed:", message)


def onopen():
    """
    Callback function to subscribe to data type and symbols upon WebSocket connection.

    """
    # Specify the data type and symbols you want to subscribe to
    data_type = "SymbolUpdate"
    # data_type= "DepthUpdate"

    # INDEX
    symbols = ['NSE:NIFTYBANK-INDEX','NSE:NIFTY50-INDEX']

    fyers.subscribe(symbols=symbols, data_type=data_type)

    # Keep the socket running to receive real-time data
    fyers.keep_running()


# Create a FyersDataSocket instance with the provided parameters
fyers = data_ws.FyersDataSocket(
    access_token=access_token,  # Access token in the format "appid:accesstoken"
    log_path="",  # Path to save logs. Leave empty to auto-create logs in the current directory.
    litemode=False,  # Lite mode disabled. Set to True if you want a lite response.
    write_to_file=False,  # Save response in a log file instead of printing it.
    reconnect=True,  # Enable auto-reconnection to WebSocket on disconnection.
    on_connect=onopen,  # Callback function to subscribe to data upon connection.
    on_close=onclose,  # Callback function to handle WebSocket connection close events.
    on_error=onerror,  # Callback function to handle WebSocket errors.
    on_message=onmessage  # Callback function to handle incoming messages from the WebSocket.
)

# Establish a connection to the Fyers WebSocket
fyers.connect()           

This program enables you to monitor real-time price changes for two specific symbols, updating the data every second.

Disassembling the code

We will now break down the code above and examine the function of each section. Subsequently, we will have a detailed understanding of how the program works.

We will import the following library from fyers api


from fyers_apiv3.FyersWebsocket import data_ws

As we already have access.txt from login and now we will store this in a variable “client-id” using this program.


with open('access.txt', 'r') as a:
    access_token = a.read()
client_id = 'your client id'

We have created a function to print the received data. Subsequently, this function will display the data whenever a response is received from the server.


def onmessage(message):
    print("Response:", message)

This is a function which will be activated when there’s an error and it will print a message.


def onerror(message):
"""
Callback function to handle WebSocket errors.

Parameters:
    message (dict): The error message received from the WebSocket.


"""
print("Error:", message)
            

This is a function which will be activated when the websocket closes. We will get a close message when it closes.


def onclose(message):
"""
Callback function to handle WebSocket connection close events.
"""
print("Connection closed:", message)

This function is the one which we will be using the most, we will specify the symbols to subscribe and the type of data we wanted.


def onopen():
"""
Callback function to subscribe to data type and symbols upon WebSocket connection.

"""
# Specify the data type and symbols you want to subscribe to
data_type = "SymbolUpdate"
# data_type= "DepthUpdate"

# INDEX
symbols = ['NSE:NIFTYBANK-INDEX','NSE:NIFTY50-INDEX']

fyers.subscribe(symbols=symbols, data_type=data_type)

# Keep the socket running to receive real-time data
fyers.keep_running()

The below code specify the parameters of websocket api, we will provide the data we have here.


# Create a FyersDataSocket instance with the provided parameters
fyers = data_ws.FyersDataSocket(
    access_token=access_token,  # Access token in the format "appid:accesstoken"
    log_path="",  # Path to save logs. Leave empty to auto-create logs in the current directory.
    litemode=False,  # Lite mode disabled. Set to True if you want a lite response.
    write_to_file=False,  # Save response in a log file instead of printing it.
    reconnect=True,  # Enable auto-reconnection to WebSocket on disconnection.
    on_connect=onopen,  # Callback function to subscribe to data upon connection.
    on_close=onclose,  # Callback function to handle WebSocket connection close events.
    on_error=onerror,  # Callback function to handle WebSocket errors.
    on_message=onmessage  # Callback function to handle incoming messages from the WebSocket.
)

The final code below will connect us to the fyers WebSocket API.


# Establish a connection to the Fyers WebSocket
fyers.connect() 

So, here are the code for live data fetching. Next up will be the program which will fetch data by date and duration. 

In the previous post, we have seen we can login to the API and also how can we get our profile and status update. You can click on “Previous” for our previous posts.


Posted

in

by

Comments

Leave a Reply

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