To obtain candlestick streams for various cryptocurrencies from Binance Websocket using Python, you can follow these steps:
import websocket
import json
import pandas as pd
from datetime import datetime
def format_candlestick(candlestick):
# convert timestamp to datetime object
timestamp = datetime.fromtimestamp(candlestick[0]/1000)
# format candlestick
formatted_candlestick = [timestamp, candlestick[1], candlestick[2], candlestick[3], candlestick[4]]
return formatted_candlestick
def on_message(ws, message):
# parse message into JSON object
message = json.loads(message)
# extract candlestick data from message
candlestick_data = message['k']
# format candlestick
formatted_candlestick = format_candlestick(candlestick_data)
# add formatted candlestick to dataframe
df_candlesticks.loc[len(df_candlesticks)] = formatted_candlestick
def connect_to_websocket(crypto_currency, interval):
# create WebSocket url
ws_url = f'wss://stream.binance.com:9443/ws/{crypto_currency.lower()}usdt@kline_{interval}'
# create WebSocket connection
ws = websocket.WebSocketApp(ws_url, on_message=on_message)
# start WebSocket connection
ws.run_forever()
df_columns = ['date', 'open', 'high', 'low', 'close']
df_candlesticks = pd.DataFrame(columns=df_columns)
connect_to_websocket('BTC', '1m')
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-06-01 18:19:20 +0000
Seen: 7 times
Last updated: Jun 01 '23
How can I set up Gunicorn with a Django Project?
Looking for a Python Module that finds Tags for a Text describing its Content
Need a Function in Python to remove entries less than 2 digits from an Array
How can I convert a Document in Python?
How can I program a Loop in Python?
How can I enable Python Code Highlighting in Askbot?