Market depth websocket connection error

Hi, I am getting error while subscribing to market depth websocket API. It was working fine till yesterday.

2024-09-18 12:48:37,228 INFO [com.opt.tra.str.UpstoxQuoteStreamApiClient] (WebSocketConnectReadThread-106) Url for websocket connection: wss://wsfeeder-api.upstox.com/market-data-feeder/v2/upstox-developer-api/feeds?requestId=01363101-59df-473d-9ec7-e4c227160be6&code=NXNC0-c96e5379-e76f-46ee-8a9e-7747f92e5fed
2024-09-18 12:48:37,370 ERROR [com.opt.tra.str.UpstoxQuoteStreamApiClient] (WebSocketConnectReadThread-108) Market feed connection closed by us. Info: Invalid status code received: 403 Status line: HTTP/1.1 403 Forbidden

@sunilsaini, please regenerate the WSS URL as it is valid for one-time use only. If you continue to experience any issues, feel free to let us know.

Thank you.

I am still facing the issue and I tried regenerating multiple times

@Ketan @Pradeep_Jaiswar Can you please look into this? Still getting same error. I think other people are also getting this error.

@sunilsaini, could you please provide your 6-digit user ID for further investigation?

Thank you!

@sunilsaini

We need more details about the issue youā€™re encountering. A connection should not be rejected unless there are numerous active connections.

Could you provide information on how many active connections you had when the rejection occurred and how many scrips youā€™ve subscribed to on each connection?

This will help us troubleshoot the issue more efficiently.

Thanks!

@shanmu
I am getting error as soon as connection is opened even when no scrip is subscribed. Although my main application is in Java, I have also tried running python example for Upstox python github repo which is also not working.

import upstox_client

def on_message(message):
    print(message)

def on_open():
    print('connection is opened')

def on_close():
    print('connection is closed')

def on_error(error):
    print('error in connection')
    print(error)


def main():
    configuration = upstox_client.Configuration()
    access_token = '<Access_Token>'
    configuration.access_token = access_token

    streamer = upstox_client.MarketDataStreamer(
        upstox_client.ApiClient(configuration), ["NSE_INDEX|Nifty 50"], "full")

    streamer.on("message", on_message)
    streamer.on('open', on_open)
    streamer.on('error', on_error)
    streamer.on('close', on_close)

    streamer.connect()


if __name__ == "__main__":
    main()

@sunilsaini

The connection rejection issue is not related to the programming language but is intentionally blocked by Upstox due to exceeding the maximum allowed number of active connections.

Please check if your application running on any server has active socket sessions. Additionally, if youā€™re using a loop mechanism to establish connections without a maximum limit, this issue is expected.

Kindly verify any active connections and terminate them before initiating new ones.

Thanks.

@shanmu I am aware that this issue is due to exceeding the maximum allowed number of active connections. But I use the python sample just to confirm that it is not due to my code making more than maximum connections allowed.
Currently there is no application running which make connection to Upstox and if it is still showing on your side then it must be showing some older connection which are no longer active, so if itā€™s possible can you please terminate those connections from your side

1 Like

@sunilsaini

Iā€™ll check on this and get back to you.

Thanks!

@shanmu any update on this issue?

I too am getting issues with websocket connection . It just hangs up after saying connection established with below code. Nothing happens. Earlier on restarting it use to stream but not today :

async def fetch_market_data(scrips, token):
    """Fetch market data using WebSocket and print it."""
    max_reconnect_delay = 60  # Maximum reconnection delay in seconds
    reconnect_delay = 5  # Initial reconnection delay in seconds
    print('Starting Websocket')

    # 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 = token

    while True:
        try:
            # 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": scrips
                    }
                }

                # 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(data_dict,'\n')
                    process_ticks_Upstox.delay(data_dict)

        except websockets.exceptions.ConnectionClosedError as e:
            logger.error(f"WebSocket connection closed unexpectedly: {e}")
            logger.info("Reconnecting in 5 seconds...")

        except Exception as e:
            logger.error(f"An error occurred: {e}")
            logger.info("Reconnecting in 5 seconds...")

        if dt.datetime.now().time() > dt.datetime.strptime('15:30', '%H:%M').time():
            logger.info("Market is closed. Exiting...")
            break

        # Wait before reconnecting
        await asyncio.sleep(reconnect_delay)  # Adjust the delay as needed
        # Implement exponential backoff
        reconnect_delay = min(2 * reconnect_delay, max_reconnect_delay)

It is streaming now on restarting the app.
Thanks

@prsh

Weā€™ve added a streamer functionality to our SDK, and we recommend using it.

For more details, check out the documentation.

Do let us know if this helps!

Thanks!

@shanmu any update on this issue? Itā€™s been two weeks since I am facing this issue.

the error is due to accesstoken .

Hi @sunilsaini,

Weā€™re currently looking into this matter and will get back to you soon.

Thanks!

Could you please try and check again, @sunilsaini?

@shanmu
The streaming is working now without issues after switching to streamer functionality. Thank for guidance.