How do I fetch live market data using websocket for attributes [“timestamp”, “open”, “high”, “low”, “close”, “volume”]. Struggling with fetching real time volume (not cumulative volume), can’t rely on ohlc quote. Please help.
As per my code below:
async def fetch_market_data(self):
"""Fetch market data using WebSocket and process it."""
# Create SSL context
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
# Get WebSocket URL
websocket_url = self.get_market_data_feed_authorize()
# Connect to WebSocket
async with websockets.connect(websocket_url, ssl=ssl_context) as websocket:
print("Connection established")
await asyncio.sleep(1) # Allow connection setup
# Subscription payload
subscription_data = {
"guid": "someguid",
"method": "sub",
"data": {
"mode": "full",
"instrumentKeys": ["NSE_EQ|INE155A01022"]
}
}
# Convert data to binary and send over WebSocket
binary_data = json.dumps(subscription_data).encode('utf-8')
await websocket.send(binary_data)
# Receive and process data continuously
while True:
message = await websocket.recv()
decoded_data = self.decode_protobuf(message)
data_dict = MessageToDict(decoded_data)
# Print the received data
print(json.dumps(data_dict, indent=2))
Output:
Connection established
{
“feeds”: {
“NSE_EQ|INE155A01022”: {
“ff”: {
“marketFF”: {
“ltpc”: {
“ltp”: 779.75,
“ltt”: “1734431384078”,
“ltq”: “26”,
“cp”: 784.8
},
“marketLevel”: {
“bidAskQuote”: [
{
“bq”: 356,
“bp”: 779.75,
“bno”: 28,
“bidQ”: “356”
},
{},
{},
{},
{}
]
},
“optionGreeks”: {},
“marketOHLC”: {
“ohlc”: [
{
“interval”: “1d”,
“open”: 785.5,
“high”: 796.35,
“low”: 778.0,
“close”: 779.75,
“volume”: 10270253,
“ts”: “1734373800000”,
“vol”: “10270253”
},
{
“interval”: “I1”,
“open”: 779.5,
“high”: 779.5,
“low”: 778.9,
“close”: 779.4,
“volume”: 29694,
“ts”: “1734429480000”,
“vol”: “29694”
},
{
“interval”: “I1”,
“open”: 779.4,
“high”: 780.0,
“low”: 778.8,
“close”: 779.9,
“volume”: 33725,
“ts”: “1734429540000”,
“vol”: “33725”
},
{
“interval”: “I30”,
“open”: 780.7,
“high”: 782.0,
“low”: 779.0,
“close”: 779.8,
“volume”: 1143290,
“ts”: “1734426900000”,
“vol”: “1143290”
},
{
“interval”: “I30”,
“open”: 779.8,
“high”: 780.0,
“low”: 778.0,
“close”: 779.9,
“volume”: 828056,
“ts”: “1734428700000”,
“vol”: “828056”
}
]
},
“eFeedDetails”: {
“atp”: 786.0,
“cp”: 784.8,
“vtt”: “10270253”,
“tbq”: 356.0,
“lc”: 706.35,
“uc”: 863.25,
“yh”: 1179.0,
“yl”: 696.25,
“fp”: 779.75,
“fv”: 26
}
}
}
}
},
“currentTs”: “1734441767479”
}