Here’s an article on obtaining real-time Ethereum data without blocking code:
Obtaining Real-Time Ethereum Data with Binance WebSocket
As a developer, you’re likely familiar with the importance of having real-time data at your fingertips. In this article, we’ll explore how to obtain and plot real-time Ethereum data from Binance using Python’s WebSocket protocol.
Prerequisites
Before we dive into the code, make sure you have:
- A Binance API key (for authentication purposes)
- A Python 3.x environment set up with a library of your choice (we recommend
websocket-client
for this example)
Importing Libraries and Configuring Binance API
import websocket
import pandas as pd
Set up Binance API credentials
api_key = "YOUR_API_KEY"
api_secret = "YOUR_API_SECRET"
Create a WebSocket object with the API endpoint (replace with your own)
ws = websocket.WebSocket()
ws.connect("wss://apis.binance.com/1/subapi")
Defining a Custom Event Handler
To receive real-time data, we need to define an event handler that listens for incoming messages from Binance. We’ll use the on_message
method provided by the WebSocket object.
def handle_message(message):
try:
Parse the message as JSON
data = json.loads(message)
Extract relevant fields (we'll ignore ETH price and exchange rate for now)
symbol = data["symbol"]
timestamp = int(data["timestamp"])
Plot a simple line chart using Pandas
df = pd.DataFrame({
'Date': [timestamp],
'ETH Price': [data["open"] * 10000]
})
Display the plot (optional)
import matplotlib.pyplot as plt
plt.plot(df['Date'], df['ETH Price'])
plt.show()
except json.JSONDecodeError:
print(f"Invalid message received: {message}")
Sending a Real-Time Plot Request to Binance
To plot real-time data, we need to send a request to Binance with our custom event handler. We’ll use the websocket_client
library to create a WebSocket object and send messages.
def send_plot_request(symbol):
try:
Create a message with the symbol and timestamp (in seconds since epoch)
msg = {
"jsonrpc": "2.0",
"method": "eth_getRealtimeBlockTimes",
"params": [
["USDT", 1, "timestamp"],
{"symbol": symbol}
],
"id": 1
}
Send the message to Binance and get the response
ws.send(json.dumps(msg).encode())
Parse the response as JSON
data = json.loads(ws.recv()).get("result")
Extract relevant fields (we'll ignore ETH price for now)
blockTimes = data["blocktimes"]
blockNumber = int(blockTimes[0])
Plot a simple line chart using Pandas
df = pd.DataFrame({
'Block Number': [blockNumber],
'Timestamp': [int(blockTimes[1])]
})
Display the plot (optional)
import matplotlib.pyplot as plt
plt.plot(df['Timestamp'], df['Block Number'])
plt.show()
except Exception as e:
print(f"Error sending plot request: {e}")
Putting it All Together
Here’s the complete code that combines all the steps:
“`python
import websocket
import pandas as pd
Set up Binance API credentials
api_key = “YOUR_API_KEY”
api_secret = “YOUR_API_SECRET”
Create a WebSocket object with the API endpoint (replace with your own)
ws = websocket.WebSocket()
ws.connect(“wss://apis.binance.com/1/subapi”)
def handle_message(message):
try:
Parse the message as JSON
data = json.