Home > front end >  Filter the response from Websocket connection
Filter the response from Websocket connection

Time:10-25

I am attempting to filter the information from a websocket request. I can complete my request fine however the response comes back with more information than I actually require. I want to filter this information out and then use it in a variable.

For example if I just use the sample code from ByBit websocket api

import json
from websocket import create_connection

ws = create_connection("wss://stream-testnet.bybit.com/realtime")
ws.send('{"op": "subscribe", "args": ["instrument_info.100ms.BTCUSD"]}');
bybitresult = ws.recv()
print(bybitresult)
ws.close()

I get the response below

{"topic":"instrument_info.100ms.BTCUSD","type":"snapshot","data":{"id":1,"symbol":"BTCUSD","last_price_e4":192785000,"last_price":"19278.50","bid1_price_e4":192780000,"bid1_price":"19278.00","ask1_price_e4":192785000,"ask1_price":"19278.50","last_tick_direction":"ZeroPlusTick","prev_price_24h_e4":192650000,"prev_price_24h":"19265.00","price_24h_pcnt_e6":700,"high_price_24h_e4":204470000,"high_price_24h":"20447.00","low_price_24h_e4":187415000,"low_price_24h":"18741.50","prev_price_1h_e4":192785000,"prev_price_1h":"19278.50","price_1h_pcnt_e6":0,"mark_price_e4":192886700,"mark_price":"19288.67","index_price_e4":193439800,"index_price":"19343.98","open_interest":467889481,"open_value_e8":0,"total_turnover_e8":1786988413378107,"turnover_24h_e8":65984748882,"total_volume":478565052570,"volume_24h":12839296,"funding_rate_e6":-677,"predicted_funding_rate_e6":-677,"cross_seq":5562806725,"created_at":"2018-12-29T03:04:13Z","updated_at":"2022-10-25T06:09:48Z","next_funding_time":"2022-10-25T08:00:00Z","countdown_hour":2,"funding_rate_interval":8,"settle_time_e9":0,"delisting_status":"0"},"cross_seq":5562806725,"timestamp_e6":1666678189180180}

However, I only want to use some of the data within the "data" string for example 'last_price' and 'timestamp_e6'. I have attempted this by trying to split the output string but am not having any luck at the moment.

Any help would be greatly appreciated. Thank you

CodePudding user response:

Convert string into dictionary, which can be achieved by using json package, so that we can get values by referring keys

  • Related