@Tradehull_Imran
Sir
Dhan have started providing 20-level market depth, but 99% of traders don’t know how to make WebSocket connections or send API requests to access the 20-level market depth.
Dhan started providing 20-level data, but if we cannot make use of it, then it is useless.
I’ve been trying but have faced many issues, and there is no one to help resolve them.
Please make make a video explaining it or provide the Python code. It would be very useful for thousands of traders.
If you truly want to help traders with your 20-level market depth data, please provide the code or make a useful video on it.
You can check out my code below.
import websocket
import json
import struct
def process_depth(raw_data):
index, output, exchange_map = 0, {"data": {}, "status": "success"}, {1: 'NSE', 2: 'NSE_FNO', 3: 'BSE', 4: 'BSE_FNO'}
header_fmt, depth_fmt, levels = '<HBBII', '<dII', 20
header_size, level_size = struct.calcsize(header_fmt), struct.calcsize(depth_fmt)
while index + header_size <= len(raw_data):
msg_len, feed_code, exch_code, sec_id, _ = struct.unpack(header_fmt, raw_data[index:index + header_size])
expected_length = header_size + (levels * level_size)
if index + expected_length > len(raw_data): break
side, exchange = {41: "buy", 51: "sell"}.get(feed_code), exchange_map.get(exch_code, f'UNKNOWN_{exch_code}')
if not side: index += msg_len; continue
output["data"].setdefault(exchange, {}).setdefault(str(sec_id), {"depth": {"buy": [], "sell": []}})
depth_data = raw_data[index + header_size: index + expected_length]
output["data"][exchange][str(sec_id)]["depth"][side] = [{
"price": round(price, 2), "quantity": qty, "orders": orders
} for price, qty, orders in struct.iter_unpack(depth_fmt, depth_data)]
index += expected_length
return output
def on_message(ws, msg): print("Received:", process_depth(msg))
def on_error(ws, err): print("Error:", err)
def on_close(ws, *_): print("WebSocket closed")
def on_open(ws):
print("Connected")
ws.send(json.dumps({
"RequestCode": 23, "InstrumentCount": 5,
"InstrumentList": [{"ExchangeSegment": "NSE_EQ", "SecurityId": str(id)} for id in [3787, 3045, 1333, 3456, 15355]] }))
def start_ws():
ws = websocket.WebSocketApp(
f"wss://depth-api-feed.dhan.co/twentydepth?token={access_token}&clientId={client_id}&authType=2",
on_message=on_message, on_error=on_error, on_close=on_close )
ws.on_open = on_open
ws.run_forever()
if __name__ == "__main__": start_ws()
Error: [Errno 104] Connection reset by peer
WebSocket closed
please make a video on how to get 20 level market data.
Please also explain, how to send multiple json requests.
Bcz we can send upto 50 instruments in single json requests.
So, I want to send multiple json requests.Howwww???