Ask Your Question
1

What is the method for obtaining candlestick-streams for various cryptocurrencies from Binance Websocket using python?

asked 2023-06-01 18:19:20 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-01 18:47:01 +0000

pufferfish gravatar image

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.
edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-06-01 18:19:20 +0000

Seen: 7 times

Last updated: Jun 01 '23