In today's fast-moving cryptocurrency markets, it's crucial to have access to real-time price data. By leveraging WebSockets in Python and creating a reactive frontend in React, we can build customizable crypto charting dashboards that update continuously with the latest pricing information.
In this comprehensive tutorial, we will:
Gain an understanding of real-time data streaming with WebSockets
Set up a Python server to retrieve live crypto prices from the CoinGecko API
Transmit the real-time data to a React frontend over a WebSocket connection
Display elegant crypto price charts that update every second as new prices come in
The result will be a responsive web app that provides up-to-the-second visibility into cryptocurrency valuations.
Prerequisites
Before we get started building our real-time crypto price dashboard, let's briefly cover the core technologies we'll be working with:
React: Frontend JavaScript library for building user interfaces
Python: Backend language for building the server app
Websockets: Communication protocol for fast, real-time data streaming
Having a basic familiarity with React components and hooks, Python scripts, setting up a Python virtual environment, and the websocket protocol will ensure we can fully understand this tutorial.
Learn how to become a Blockchain Engineer with this guide.
Project Setup
With our dependencies installed, let's set up a new React project and a basic Python server.
We'll use create-react-app to scaffold our frontend:
npx create-react-app crypto-price-app
And then build an API server in a server.py file:
#server.py
import websocket
import json
# Websocket setup...
We'll flesh out the Python later. But for now, our frontend React app will connect to the API server at 'ws://localhost:8080'.
Getting Live Crypto Prices
Now let's work on our Python server to supply real-time crypto price data to the React frontend.
We'll use the CoinGecko API - a free crypto API that's robust, consistent and offers detailed docs.
After signing up and grabbing our API key, we'll define a fetchPrices
function to retrieve the latest BTC and ETH prices:
# Fetches latest BTC, ETH prices from CoinGecko API
def fetchPrices():
cg = CoinGeckoAPI(api_key)
btc_data = cg.get_price(ids='bitcoin', vs_currencies='usd')
eth_data = cg.get_price(ids='ethereum', vs_currencies='usd')
btc_price = btc_data\['bitcoin'\]['usd']
eth_price = eth_data\['ethereum'\]['usd']
data = {
"btc": btc_price,
"eth": eth_price
}
return json.dumps(data)
We make two API calls to get the individual Bitcoin and Ethereum prices, which we consolidate into a JSON payload before returning.
Setting Up The Websocket
Next, we must create a WebSocket endpoint emitting crypto price updates. The Python websocket-client module makes this straightforward:
import websocket
import json
# On new websocket connection
def on_open(ws):
print("Websocket connection opened")
# On new message received
def on_message(ws, message):
print("Message received:")
print(message)
def run_websocket_server():
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://localhost:8080",
on_open=on_open,
on_message=on_message)
ws.run_forever()
Here we open a websocket connection, define callbacks for new events, and fall into a perpetual run loop to keep the server alive.
Now let's emit price updates every second by invoking fetchPrices and sending the JSON payload out to clients:
import time
while True:
prices = fetchPrices()
ws.send(prices)
time.sleep(1)
Our Python backend continuously scrapes the latest crypto valuations and broadcasts them through our websocket.
Connecting React to the Websocket
Shifting to our React frontend, let's wire up a connection to the running Python websocket server.
We'll use the popular react-use-websocket hook to abstract away websocket complexity:
// App.js
import { useState, useEffect } from 'react';
import { useWebSocket } from 'react-use-websocket';
export default () => {
// Websocket hooks
const [socketUrl] = useState('ws://localhost:8080');
const {lastMessage} = useWebSocket(socketUrl);
useEffect(() => {
if (lastMessage !== null) {
console.log(lastMessage);
// Update component state
}
}, [lastMessage]);
return (
// React component
)
This establishes a persistent connection to our websocket endpoint, invoking the callback whenever a new message comes through.
Here, we simply log the message containing our real-time crypto prices to the console.
Next, let's properly handle these updates within React's state.
Processing Streaming Data
To display real-time charts, our React app needs to track the incoming price data in state.
Whenever we receive an update from our Python server, we'll decode the JSON payload and update state.
// Hook to store price data in state
const [priceData, setPriceData] = useState({});
useEffect(() => {
if (lastMessage !== null) {
const data = JSON.parse(lastMessage.data);
setPriceData(data);
}
}, [lastMessage]);
Our priceData
state will now always reflect the latest prices.
React Crypto Charting
Finally, we can connect our state to React charting libraries to display elegant, real-time graphs.
Using Chart.js
, for example, we pass our streaming price state into the chart data, causing a smooth animation on every update:
// Price chart
import { Line } from 'react-chartjs-2';
const chartData = {
datasets: [
{
label: 'BTC',
data: priceData.btc // updated in real-time!
}
]
}
return (
<div className="chart-wrapper">
<Line data={chartData} />
</div>
)
[
](dev.to/new#conclusion)
Conclusion
And there we have it - a comprehensive, real-time crypto charting dashboard in React!
By leveraging websockets, we tapped into a constant stream of up-to-date price data.
Our Python server fetches valuations and funnels them to React via a persistent websocket connection, keeping state in sync.
There are plenty of additional features we could build, like:
Tracking historical pricing data
Supporting more crypto assets
Implementing user accounts and portfolios
But our application already unlocks the fundamentals of combining Python and React with websockets for a dynamic, data-intensive experience.
The crypto world never sleeps, so having 24/7 visibility into price fluctuations is invaluable. Our charting dashboard provides precisely that - unlocking the real power of real-time data.