Please help me guys regarding WebSocket (v3 API)

Hi Upstox API Team,

I am using the Upstox API for real-time market data analysis.

My API Client ID: f7839b11-2fec-4fb1-9f0d-d2823ab577ce
App Name: My option chain

I am able to authenticate and connect to the WebSocket V3 URL successfully. However, I am not receiving any tick data for any instrument.

Can you please check and confirm if Market Data WebSocket V3 access is enabled for my API key?
If not, kindly enable the Market Data V3 WebSocket access.
i am doing this for nifty jul fut which has instrument key NSE_FO|53216 , please debug my issue urgently as i have to develop my app,
Earlier response will be highly appriciated
I had did every thing like proto decoding file but still not receiving any tick data.
Thanks,
Yash Jindal

take ai help u will get the soln

Abhishek ,I tried and did every possible things can you please help me in this stuff

mr yash i can only show you path just try again when i am saying you answer lies in AI, try every AI and you will get your answer

Hi @YASH_34906462 No additional access is required for the Market Data V3 WebSocket.

Please refer to the sample V3 WebSocket example for guidance on properly encoding and decoding the payload.

See if this helps resolve the issue. If the problem persists, please share your code so we can assist you further with debugging.

Thanks

async def start_async_websocket():
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

while True:
    try:
        # 🆕 Always get fresh URL inside loop
        v3_auth = requests.get(
            "https://api.upstox.com/v3/feed/market-data-feed/authorize",
            headers={"Authorization": f"Bearer {access_token}"}
        )
        ws_url = v3_auth.json().get("data", {}).get("authorized_redirect_uri")
        if not ws_url:
            print("❌ Failed to get fresh WebSocket URL:", v3_auth.json())
            await asyncio.sleep(5)
            continue

        async with connect(ws_url, ssl=ssl_context, extra_headers={
            "Authorization": f"Bearer {access_token}",
            "x-api-key": api_key
        }) as websocket:
            print("✅ Connected to Upstox V3 WebSocket")

           # ✅ Correct Protobuf Subscription Send Code
            sub = pb.FeedRequest()
            sub.guid = "guid-123"
            sub.subscription.action = "sub"
            sub.subscription.mode = pb.full_d30
            sub.subscription.instrument_keys.append("NSE_FO|53216")

            await websocket.send(sub.SerializeToString())



            # Start receiving messages
            while True:
                message = await websocket.recv()
                print(f"📨 Received message of type: {type(message)} | length: {len(message)}")
                print("📩 RAW BYTES:", message[:20])  # show first 20 bytes

                # ✅ Protobuf binary data
                if isinstance(message, bytes):
                    proto_msg = pb.FeedResponse()
                    try:
                        proto_msg.ParseFromString(message)
                        print("📦 Protobuf Message Dump:")
                        print(proto_msg)

                    except Exception as e:
                        print("❌ Protobuf Decode Error:", e)
                        continue  # ✅ Only skip if decoding fails

                    for instrument_key, feed_entry in proto_msg.feeds.items():
                        if feed_entry.HasField("fullFeed") and feed_entry.fullFeed.HasField("marketFF"):
                            market_data = feed_entry.fullFeed.marketFF

                            ltp = market_data.ltpc.ltp
                            ltq = market_data.ltpc.ltq
                            ltt = datetime.fromtimestamp(market_data.ltpc.ltt / 1000).strftime("%H:%M:%S")

                            depth_data = {
                                "buy": [{"size": q.bidQ} for q in market_data.marketLevel.bidAskQuote],
                                "sell": [{"size": q.askQ} for q in market_data.marketLevel.bidAskQuote]
                            }

                            tick_data = {
                                "ltp": ltp,
                                "ltq": ltq,
                                "ltt": ltt,
                                "depth": depth_data
                            }

                            print(f"📥 Tick: {ltp} Qty: {ltq} @ {ltt}")
                            depth = proc.process_depth(tick_data)
                            proc.process(tick_data, depth)

    except Exception as e:
        print("❌ WebSocket Error:", e)
        print("🔁 Retrying in 5 seconds...")
        await asyncio.sleep(5)

OUTPUT OF THE CODE :-
:locked_with_key: Requesting Access Token…
:white_check_mark: Access Token Acquired!

:white_check_mark: Connected to Upstox V3 WebSocket
:incoming_envelope: Received message of type: <class ‘bytes’> | length: 165
:envelope_with_arrow: RAW BYTES: b’\x08\x02\x18\xf4\xa0\xe8\xa5\xfc2"\x99\x01\n\x0b\n\x07NSE_’
:package: Protobuf Message Dump:
type: market_info
currentTs: 1751352217716
marketInfo {
segmentStatus {
key: “US_EQ”
value: NORMAL_CLOSE
}
segmentStatus {
key: “NSE_INDEX”
value: NORMAL_OPEN
}
segmentStatus {
key: “NSE_FO”
value: NORMAL_OPEN
}
segmentStatus {
key: “NSE_EQ”
value: NORMAL_OPEN
}
segmentStatus {
key: “NSE_COM”
value: NORMAL_OPEN
}
segmentStatus {
key: “NCD_FO”
value: NORMAL_OPEN
}
segmentStatus {
key: “MCX_INDEX”
value: NORMAL_OPEN
}
segmentStatus {
key: “MCX_FO”
value: NORMAL_OPEN
}
segmentStatus {
key: “BSE_INDEX”
value: NORMAL_OPEN
}
segmentStatus {
key: “BSE_FO”
value: NORMAL_OPEN
}
segmentStatus {
key: “BSE_EQ”
value: NORMAL_OPEN
}
segmentStatus {
key: “BCD_FO”
value: NORMAL_OPEN
}
}

"Sir, I’m facing this issue for the last 6 days and it has completely halted my trading setup. I’ve tried sending client-to-server requests in both JSON and Protobuf formats. The code I’m currently using is in Protobuf, but I’m still not receiving any ticks. Below is the output I’m getting.

I’ve tried multiple ways but nothing seems to work. Kindly guide me with the correct approach. Your help will be highly appreciated!"

Hi @YASH_34906462 , It doesn’t look like we have a FeedRequest defined in the proto.

sub = pb.FeedRequest()
sub.guid = "guid-123"
sub.subscription.action = "sub"
sub.subscription.mode = pb.full_d30
sub.subscription.instrument_keys.append("NSE_FO|53216")

await websocket.send(sub.SerializeToString())

Instead, please try the approach shown below, as outlined in the sample WebSocket example. It should work as expected:

  # Data to be sent over the WebSocket
  data = {
      "guid": "guid-123",
      "method": "sub",
      "data": {
          "mode": "full_d30",
          "instrumentKeys": ["NSE_FO|53216"]
      }
  }

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

Let us know if you face any further issues.

Sir, thank you! This started working. I just have one last question, and I would be really grateful if you could help.

I want to run 3 WebSocket connections at the same time. Could you please guide me with a very basic implementation for that? Whenever I try, only one WebSocket connects successfully, but the other two show a 403 error.

Here’s how I currently created the 3 WebSockets:
async def run_spot_socket(access_token):
v3_auth_url = “https://api.upstox.com/v3/feed/market-data-feed/authorize
headers = {
“accept”: “application/json”,
“Authorization”: f"Bearer {access_token}"
}

try:
    response = requests.get(v3_auth_url, headers=headers)
    response.raise_for_status()
    v3_ws_url = response.json().get("data", {}).get("authorizedRedirectUri", "")
    if not v3_ws_url:
        print("❌ WebSocket URL missing in response.")
        return
    print("✅ V3 WebSocket URL:", v3_ws_url)
except Exception as e:
    print("❌ Failed to fetch V3 WebSocket URL:", e)
    return

ssl_context = ssl.create_default_context()

try:
    async with connect(
        v3_ws_url,
        extra_headers={"Authorization": f"Bearer {access_token}"},
        ssl=ssl_context,
        max_size=None
    ) as ws:
        await subscribe_spot_fut(ws)
        async for message in ws:
            await handle_spot_message(message)

except websockets.WebSocketException as ws_err:
    print("🔴 WebSocket Error (spot):", ws_err)

except Exception as e:
    print("❌ General Error (spot):", e)

OUTPUT

:white_check_mark: Access Token Fetched
:white_check_mark: V3 WebSocket URL: wss://wsfeeder-api.upstox.com/market-data-feeder/v3/upstox-developer-api/feeds?requestId=0b9e7de1-2ad2-4374-9d6f-c215e2b5b105&code=OOgZJ-2d33fc85-3c7a-4706-acc8-4c800e87b0ce
:white_check_mark: V3 WebSocket URL: wss://wsfeeder-api.upstox.com/market-data-feeder/v3/upstox-developer-api/feeds?requestId=cd7615f7-e38f-4d7b-aa2a-c3b557c1631e&code=hv3hb-8ff9bd4a-afcc-4f84-8acd-4084c1c7b809
:white_check_mark: V3 WebSocket URL: wss://wsfeeder-api.upstox.com/market-data-feeder/v3/upstox-developer-api/feeds?requestId=ad7ebbc6-5399-486f-aec9-5df925c06d69&code=zM0C2-b1a74def-7643-4c28-ba68-03608bbbd509
:white_check_mark: PE WebSocket Subscribed.
:red_circle: WebSocket Error (spot): server rejected WebSocket connection: HTTP 403
:cross_mark: WebSocket Connection Error: server rejected WebSocket connection: HTTP 403
Only the last WebSocket runs successfully; all the others fail.

Hi @YASH_34906462 Kindly review the connection and subscription limits outlined Market Data Feed V3 | Upstox Developer API