20 MARKET DEPTH ( 20 Market Depth - DhanHQ Ver 2.0 / API Document) NOT RETURNING ANYTHING. KINDLY HELP @RahulDeshpande
import struct
import logging
import websocket
import json
import threading
import time
from datetime import datetime
logging.basicConfig(level=logging.DEBUG)
CLIENT_CODE = ""
TOKEN_ID = ""
# Test with fewer instruments for debugging
sub_msg = {
"RequestCode": 23,
"InstrumentCount": 2,
"InstrumentList": [
{"ExchangeSegment": "NSE_FNO", "SecurityId": "35009"},
{"ExchangeSegment": "NSE_FNO", "SecurityId": "35010"}
]
}
live_20_depth_data = {inst['SecurityId']: {'bid': [], 'ask': [], 'last_update': None} for inst in sub_msg['InstrumentList']}
print(f"Initialized live_20_depth_data with keys: {list(live_20_depth_data.keys())}")
def parse_20_depth_packet(binary_message):
"""Parse binary packet."""
try:
logging.debug("Raw binary message: %s", binary_message.hex())
header_format = '<hBBII'
depth_record_format = '<dII'
header_size = struct.calcsize(header_format)
depth_record_size = struct.calcsize(depth_record_format)
msg_length, response_code, exchange_segment, security_id, seq_num = struct.unpack(header_format, binary_message[:header_size])
logging.debug(f"Header parsed: Length={msg_length}, Code={response_code}, Segment={exchange_segment}, SecurityId={security_id}, SeqNum={seq_num}")
offset = header_size
bid_depth, ask_depth = [], []
if response_code == 41:
for i in range(20):
price, qty, orders = struct.unpack(depth_record_format, binary_message[offset:offset + depth_record_size])
bid_depth.append((price, qty, orders))
offset += depth_record_size
return bid_depth, None, security_id
elif response_code == 51:
for i in range(20):
price, qty, orders = struct.unpack(depth_record_format, binary_message[offset:offset + depth_record_size])
ask_depth.append((price, qty, orders))
offset += depth_record_size
return None, ask_depth, security_id
return None, None, None
except Exception as e:
logging.exception("Error parsing packet")
return None, None, None
def on_message(ws, message):
"""Handle incoming WebSocket messages."""
if isinstance(message, bytes):
logging.debug(f"Binary message received: {message.hex()}")
parse_20_depth_packet(message)
else:
logging.debug(f"Non-binary message received: {message}")
def on_open(ws):
"""Handle WebSocket connection open."""
logging.info("Websocket connected")
sub_message = json.dumps(sub_msg)
ws.send(sub_message)
logging.info(f"Subscription sent: {sub_message}")
def start_websocket():
"""Start WebSocket feed."""
ws_url = f"wss://depth-api-feed.dhan.co/twentydepth?token={TOKEN_ID}&clientId={CLIENT_CODE}&authType=2"
ws = websocket.WebSocketApp(
ws_url,
on_open=on_open,
on_message=on_message,
on_error=lambda ws_, msg_: logging.error(f"WebSocket error: {msg_}"),
on_close=lambda ws_, code_, msg_: logging.info(f"WebSocket closed")
)
ws.run_forever(ping_interval=30)
if __name__ == "__main__":
threading.Thread(target=start_websocket).start()
PS D:\ALGO> PY '.\20 MARKET DEPTH DATA.py'
Initialized live_20_depth_data with keys: ['35009', '35010']
INFO:websocket:Websocket connected
INFO:root:Websocket connected
INFO:root:Subscription sent: {"RequestCode": 23, "InstrumentCount": 2, "InstrumentList": [{"ExchangeSegment": "NSE_FNO", "SecurityId": "35009"}, {"ExchangeSegment": "NSE_FNO", "SecurityId": "35010"}]}
DEBUG:websocket:Sending ping
DEBUG:websocket:Sending ping
DEBUG:websocket:Sending ping
DEBUG:websocket:Sending ping