May 14, 2024

Boulama

Tutorials

Real-Time Stock Price Chart with SocketBee, Python, and Vue.js

In this demo showcasing the capabilities of SocketBee, we have created a graph representing a company's stock price in real time. In this tutorial, we will go over how to recreate it using SocketBee's official clients for JavaScript and Python. Prerequisites

Before we start, make sure you have the following installed on your system:

  • Python 3.x
  • Node.js (v12 or later)
  • npm (comes bundled with Node.js)

Step 1: Set up the Python Environment

  1. Create a new directory for your project and navigate to it in your terminal.
mkdir stock-price-chart
cd stock-price-chart
  1. Create a new virtual environment for your Python project.
python3 -m venv env
  1. Activate the virtual environment.
source env/bin/activate  # On Windows, use `env\Scripts\activate`
  1. Install the required Python libraries.
pip install numpy socketbee
  1. Create a new file called server.py and open it in your preferred code editor.

Step 2: Write the Python Server Code

Paste the following code into server.py:

import time
import numpy as np
from socketbee.client import SocketBee

# Connect to SocketBee
opts = {
    'secret': 'your_secret_key',
    'client_events': 'true'
}
s = SocketBee('your_public_key', 'your_client_id', opts).connect()

while True:
    # Generate random stock price data
    stock_price = np.random.randint(15, 25)

    # Create the event data
    event_data = {
        'stock_price': stock_price
    }

    # Broadcast the event data to SocketBee
    s.broadcast('stock_price_update', event_data, 'stock_channel')

    # Wait for 1 second before sending the next update
    time.sleep(1)

Replace 'your_secret_key', 'your_public_key', and 'your_client_id' with your actual SocketBee credentials.

Here is how the code above works, and what it does:

  1. We import the necessary libraries: time for adding delays, numpy for generating random numbers, and socketbee.client for interacting with SocketBee.
  2. We connect to SocketBee by providing our credentials and creating a SocketBee instance.
  3. Inside the while loop, we generate a random stock price between 15 and 25 using np.random.randint.
  4. We create an event data dictionary with the stock price.
  5. We broadcast the event data to SocketBee using the broadcast method, specifying the event name 'stock_price_update' and the channel name 'stock_channel'.
  6. We add a delay of 1 second using time.sleep(1) before sending the next update.

Step 3: Set up the Vue.js Application

  1. Open a new terminal window and navigate to your project directory.
cd stock-price-chart
  1. Create a new Vue.js project using the Vue CLI.
npm install -g @vue/cli
vue create frontend

Follow the prompts to configure your Vue.js project.

  1. Once the project is set up, navigate to the frontend directory.
cd frontend
  1. Install the required dependencies.
npm install @socketbee/client apexcharts vue-apexcharts
  1. Open the frontend directory in your code editor.

Step 4: Write the Vue.js Code

Here is an overview of what we will do:

  1. We import the necessary libraries: SocketBeeClient for interacting with SocketBee, and ref and onMounted from Vue for reactivity and lifecycle hooks.
  2. We initialize the series and chartOptions data for ApexCharts.
  3. We create a new SocketBeeClient instance and connect to SocketBee using our credentials.
  4. Inside the onMounted hook, we subscribe to the 'stock_channel' and listen for the 'stock_price_update' event.
  5. When a stock price update is received, we update the chart data by pushing the new stock price to the series data and adding a new category (timestamp) to the chartOptions.

Let's go step by step.

  1. Create a new component called StockChart.vue in the src/components directory.
  2. Paste the following code into StockChart.vue:
<template>
  <div>
    <apexchart
      type="line"
      :options="chartOptions"
      :series="series"
    ></apexchart>
  </div>
</template>

<script>
import SocketBeeClient from "@socketbee/client";
import { ref, onMounted } from "vue";

export default {
  setup() {
    const series = ref([
      {
        name: "Stock Price",
        data: [],
      },
    ]);

    const chartOptions = ref({
      chart: {
        id: "stock-price-chart",
      },
      xaxis: {
        categories: [],
      },
    });

    // Connect to SocketBee
    const s = new SocketBeeClient(
      "your_public_key",
      "your_client_id",
      {
        client_events: false,
        port: 443,
        server: "east-1.socket.socketbee.com",
      }
    );

    onMounted(() => {
      // Subscribe to the stock channel
      const channel = s.subscribe("stock_channel", (...args) => {});

      // Listen for stock price updates
      channel.listen("stock_price_update", (...args) => {
        const stockPrice = args[0].stock_price;

        // Update the chart data
        series.value[0].data.push(stockPrice);
        chartOptions.value.xaxis.categories.push(new Date().toLocaleTimeString());
      });
    });

    return {
      series,
      chartOptions,
    };
  },
};
</script>

Replace 'your_public_key' and 'your_client_id' with your actual SocketBee credentials.

  1. Open src/App.vue and replace the content with the following:
<template>
  <div id="app">
    <StockChart />
  </div>
</template>

<script>
import StockChart from "./components/StockChart.vue";

export default {
  name: "App",
  components: {
    StockChart,
  },
};
</script>

Step 5: Run the Applications

  1. In the terminal window where you activated the Python virtual environment, run the Python server:
python server.py
  1. In the other terminal window, start the Vue.js development server:
npm run serve
  1. Open your web browser and navigate to http://localhost:8080. You should see a real-time stock price chart updating every second.

Congratulations! You have successfully built a real-time stock price chart application using SocketBee for bi-directional communication between the Python server and Vue.js frontend. This tutorial covered the following key concepts:

  • Setting up a Python environment and installing required libraries
  • Writing a Python script to simulate stock price data and broadcast it to SocketBee
  • Creating a Vue.js application and integrating it with SocketBee
  • Rendering real-time stock price data using ApexCharts

This little app demonstrates the power of SocketBee in facilitating real-time communication between servers and clients. By leveraging WebSockets, you can build highly responsive and interactive applications that update seamlessly as new data becomes available.

While this tutorial focused on a stock price chart, the concepts you learned can be applied to various other scenarios that require real-time data updates, such as live dashboards, chat applications, multiplayer games, and more. SocketBee has many more applications and use cases to explore.

Feel free to explore the SocketBee documentation (coming soon) and examples to learn more about what you can build with SocketBee. Additionally, you can integrate other libraries and frameworks with SocketBee to build more complex and feature-rich applications.

If you haven't already, request an invite for a free SocketBee account and start building your own real-time applications today!