I am running the following code on a Jupyter Notebook with testing purposes:
import json
import datetime
from binance.websocket.spot.websocket_client import SpotWebsocketClient
def safe_json_load(message):
try:
return json.loads(message)
except:
return {}
def message_handler(message):
if not isinstance(message, dict):
message = safe_json_loads(message)
if isinstance(message, dict) and 'E' in message and 's' in message and 'c' in message:
timestamp = datetime.datetime.utcfromtimestamp(int(message['E'])/1000)
last_price = float(message['c'])
output = {
'timestamp': timestamp,
'symbol': message['s'],
'price': last_price
}
print(output)
else:
print(message)
wss_client = SpotWebsocketClient(stream_url="wss://stream.binance.com:9443")
wss_client.start()
# Live subscription
wss_client.ticker(
symbol='hbarusdt@ticker',
id=1,
callback=message_handler
)
When building the message handler I was able to retrieve the symbol information. However at certain time it stopped to print the data. I have checked that if set the ticker symbol to hbarusdt
instead of hbarusdt@ticker
it prints data again but, why was it working before and not now?
Also, I would like to now how can I remove the live subscription in a similar way as I am creating it? In the future I want to deploy the solution to the cloud as a data scraper, so I may need to first try to remove previously existing subscriptions with the same ID in case the script fails and I need to start it again.