RuntimeError: asyncio.run() cannot be called from a running event loop while using python

Import necessary modules

import asyncio
import json
import ssl
import upstox_client
import websockets
from google.protobuf.json_format import MessageToDict

import MarketDataFeed_pb2 as pb

filename = f"accessToken.txt"
with open(filename,“r”) as file:
access_token = file.read

def get_market_data_feed_authorize(api_version, configuration):
“”“Get authorization for market data feed.”“”
api_instance = upstox_client.WebsocketApi(
upstox_client.ApiClient(configuration))
api_response = api_instance.get_market_data_feed_authorize(api_version)
return api_response

def decode_protobuf(buffer):
“”“Decode protobuf message.”“”
feed_response = pb.FeedResponse()
feed_response.ParseFromString(buffer)
return feed_response

async def fetch_market_data():
“”“Fetch market data using WebSocket and print it.”“”

# Create default SSL context
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

# Configure OAuth2 access token for authorization
configuration = upstox_client.Configuration()

api_version = '2.0'
configuration.access_token = access_token

# Get market data feed authorization
response = get_market_data_feed_authorize(
    api_version, configuration)

# Connect to the WebSocket with SSL context
async with websockets.connect(response.data.authorized_redirect_uri, ssl=ssl_context) as websocket:
    print('Connection established')

    await asyncio.sleep(1)  # Wait for 1 second

    # Data to be sent over the WebSocket
    data = {
        "guid": "someguid",
        "method": "sub",
        "data": {
            "mode": "full",
            "instrumentKeys": ["NSE_INDEX|Nifty Bank", "NSE_INDEX|Nifty 50"]
        }
    }

    # Convert data to binary and send over WebSocket
    binary_data = json.dumps(data).encode('utf-8')
    await websocket.send(binary_data)

    # Continuously receive and decode data from WebSocket
    while True:
        message = await websocket.recv()
        decoded_data = decode_protobuf(message)

        # Convert the decoded data to a dictionary
        data_dict = MessageToDict(decoded_data)

        # Print the dictionary representation
        print(json.dumps(data_dict))

Execute the function to fetch market data

asyncio.run(fetch_market_data())

RuntimeError Traceback (most recent call last)
Input In [9], in <cell line: 82>()
78 print(json.dumps(data_dict))
81 # Execute the function to fetch market data
—> 82 asyncio.run(fetch_market_data())
83 # Assuming fetch_all is an instance method of a class
84 def fetch_all(self, web_paths):

File C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\runners.py:33, in run(main, debug)
9 “”“Execute the coroutine and return the result.
10
11 This function runs the passed coroutine, taking care of
(…)
30 asyncio.run(main())
31 “””
32 if events._get_running_loop() is not None:
—> 33 raise RuntimeError(
34 “asyncio.run() cannot be called from a running event loop”)
36 if not coroutines.iscoroutine(main):
37 raise ValueError(“a coroutine was expected, got {!r}”.format(main))

RuntimeError: asyncio.run() cannot be called from a running event loop

The error message you are seeing, RuntimeError: asyncio.run() cannot be called from a running event loop, indicates that you are trying to use the asyncio.run() function while there is already an active event loop running. This typically happens in interactive environments like Jupyter notebooks, where an event loop is often already running in the background.

For simpler implementation please refer to Websocket Streamer Functionality
Feel free to comment if any further assistance is required in websocket implementations, Thank you

Thanks ketan for your help. Now I tried Websocket Streamer Functionality code for data feed and i got response.

But, I am not getting tick by tick data, I am getting only one time response from streamer.
Please help.

You will receive tick-by-tick data only during market hours. When the market is closed, our websocket provides the last traded price.

Please check the data during market hours and let us know if you encounter the same issue.
For more information about websockets please refer our API Documentation | Websocket

Thanks a lot. market dadafeed is not providing banknifty options live feeds ???

plz help