Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To obtain candlestick streams for various cryptocurrencies from Binance Websocket using Python, you can follow these steps:

  1. Import the necessary libraries:
import websocket
import json
import pandas as pd
from datetime import datetime
  1. Define a function to format the candlesticks:
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
  1. Define a function to handle the WebSocket message:
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
  1. Define a function to connect to the WebSocket and subscribe to candlestick streams:
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()
  1. Create a pandas dataframe to store the candlesticks:
df_columns = ['date', 'open', 'high', 'low', 'close']
df_candlesticks = pd.DataFrame(columns=df_columns)
  1. Call the connecttowebsocket() function with the desired crypto currency and interval:
connect_to_websocket('BTC', '1m')
  1. The candlestick data will be stored in the df_candlesticks dataframe. You can perform further analysis or visualization on the data as desired.