Websocket is throwing error

Hi, while tryingto connect Market data websocket, it is giving me following eroor-
Exception in thread Thread-68 (run_websocket):
Traceback (most recent call last):
File “C:\Users\600023674\AppData\Local\Programs\Python\Python313\Lib\threading.py”, line 1041, in _bootstrap_inner
self.run()
~~~~~~~~^^
File “C:\Users\600023674\AppData\Local\Programs\Python\Python313\Lib\site-packages\ipykernel\ipkernel.py”, line 766, in run_closure
_threading_Thread_run(self)
~~~~~~~~~~~~~~~~~~~~~^^^^^^
File “C:\Users\600023674\AppData\Local\Programs\Python\Python313\Lib\threading.py”, line 992, in run
self._target(*self._args, **self._kwargs)
~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\600023674\AppData\Local\Temp\ipykernel_18032\1936526626.py”, line 84, in run_websocket
loop.run_until_complete(fetch_market_data())
~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\600023674\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py”, line 721, in run_until_complete
return future.result()
~~~~~~~~~~~~~^^
File “C:\Users\600023674\AppData\Local\Temp\ipykernel_18032\1936526626.py”, line 69, in fetch_market_data
decoded_data = decode_protobuf(message)
File “C:\Users\600023674\AppData\Local\Temp\ipykernel_18032\1936526626.py”, line 22, in decode_protobuf
feed_response = pb.feed_response()
^^^^^^^^^^^^^^^^
AttributeError: module ‘MarketDataFeed_pb2’ has no attribute ‘feed_response’

NameError Traceback (most recent call last)
Cell In[8], line 92
90 while True:
91 sleep(1)
—> 92 print(‘Buysignal’, data_dict)

NameError: name ‘data_dict’ is not defined

My code is as same, snall tweaking -
Import necessary modules
import asyncio
import json
import ssl
import upstox_client
import websockets
from google.protobuf.json_format import MessageToDict
from threading import Thread
import MarketDataFeed_pb2 as pb
from time import sleep

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.feed_response()
feed_response.ParseFromString(buffer)
return feed_response

async def fetch_market_data():
“”“Fetch market data using WebSocket and print it.”“”
global data_dict
# 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())

def run_websocket():
loop=asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(fetch_market_data())

websocket_thread = Thread(target = run_websocket)
websocket_thread.start()

sleep(5)
while True:
sleep(1)
print(‘Buysignal’, data_dict)

It appears that your code is referencing a variable data_dict which hasn’t been defined. Please define this variable and try again.

For a smoother implementation of websockets, you may refer to the streamer functionalities available in different languages:

Hi Ketan,
I am receiving following error

Exception in thread Thread-35 (run_websocket):
Traceback (most recent call last):
  File "C:\Users\600023674\AppData\Local\Programs\Python\Python313\Lib\threading.py", line 1041, in _bootstrap_inner
    self.run()
    ~~~~~~~~^^
  File "C:\Users\600023674\AppData\Local\Programs\Python\Python313\Lib\site-packages\ipykernel\ipkernel.py", line 766, in run_closure
    _threading_Thread_run(self)
    ~~~~~~~~~~~~~~~~~~~~~^^^^^^
  File "C:\Users\600023674\AppData\Local\Programs\Python\Python313\Lib\threading.py", line 992, in run
    self._target(*self._args, **self._kwargs)
    ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\600023674\AppData\Local\Temp\ipykernel_27040\344112406.py", line 84, in run_websocket
    loop.run_until_complete(fetch_market_data())
    ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\600023674\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 721, in run_until_complete
    return future.result()
           ~~~~~~~~~~~~~^^
  File "C:\Users\600023674\AppData\Local\Temp\ipykernel_27040\344112406.py", line 69, in fetch_market_data
    decoded_data = decode_protobuf(message)
  File "C:\Users\600023674\AppData\Local\Temp\ipykernel_27040\344112406.py", line 22, in decode_protobuf
    feed_response = pb.feed_response()
                    ^^^^^^^^^^^^^^^^
AttributeError: module 'MarketDataFeed_pb2' has no attribute 'feed_response'

Please find attached my code.

(Attachment MarketDataFeed_pb2.py is missing)

(Attachment Upstox.ipynb is missing)

Please ignore earlier email. please find attached websocket code.

(Attachment MarketDataFeed_pb2.py is missing)

(Attachment web_socket_data.ipynb is missing)

Hi @Rahul_Sachan, I didn’t receive the files you were trying to send.
Could you please try using the streamer functions for the websocket as mentioned in my previous comment They’re easy to use, and no proto implementation is required when using the streamer functions.

Thank you,