Skip to main content
The financial industry is extremely data-heavy and relies on real-time and historical data for decision-making, risk assessment, fraud detection, and market analysis. simplifies management of these large volumes of data, while also providing you with meaningful analytical insights and optimizing storage costs. This tutorial shows you how to ingest real-time time-series data into using a websocket connection. The tutorial sets up a data pipeline to ingest real-time data from our data partner, Twelve Data. Twelve Data provides a number of different financial APIs, including stock, cryptocurrencies, foreign exchanges, and ETFs. It also supports websocket connections in case you want to update your database frequently. With websockets, you need to connect to the server, subscribe to symbols, and you can start receiving data in real-time during market hours. When you complete this tutorial, you’ll have a data pipeline set up that ingests real-time financial data into your . This tutorial uses Python and the API wrapper library provided by Twelve Data. This tutorial covers:
  1. Set up your dataset: connect to the Twelve Data websocket server, create s, and ingest real-time cryptocurrency data.
  2. Query your data: create s to aggregate OHLCV data, query the aggregated data, and visualize the data in Grafana.

Prerequisites

To follow the steps on this page:
  • Create a target with Real-time analytics enabled.

    You need your connection details. This procedure also works for .

About OHLCV data and candlestick charts

The financial sector regularly uses candlestick charts to visualize the price change of an asset. Each candlestick represents a time period, such as one minute or one hour, and shows how the asset’s price changed during that time. Candlestick charts are generated from the open, high, low, close, and volume data for each financial asset during the time period. This is often abbreviated as OHLCV:
  • Open: opening price
  • High: highest price
  • Low: lowest price
  • Close: closing price
  • Volume: volume of transactions
candlestick is well suited to storing and analyzing financial candlestick data, and many community members use it for exactly this purpose.

Ingest data into a service

This tutorial uses a dataset that contains second-by-second cryptocurrency trade data, in a named crypto_ticks. It also includes a separate table of cryptocurrency symbols and names, in a regular table named crypto_assets.

Connect to the websocket server

When you connect to the Twelve Data API through a websocket, you create a persistent connection between your computer and the websocket server. You set up a Python environment, and pass two arguments to create a websocket object and establish the connection.

Set up a new Python environment

Create a new Python virtual environment for this project and activate it. All the packages you need to complete for this tutorial are installed in this environment.
  1. Create and activate a Python virtual environment:
  2. Install the Twelve Data Python wrapper library with websocket support. This library allows you to make requests to the API and maintain a stable websocket connection.
  3. Install Psycopg2 so that you can connect the from your Python script:

Create the websocket connection

A persistent connection between your computer and the websocket server is used to receive data for as long as the connection is maintained. You need to pass two arguments to create a websocket object and establish connection. Websocket arguments
  • on_event This argument needs to be a function that is invoked whenever there’s a new data record is received from the websocket:
    This is where you want to implement the ingestion logic so whenever there’s new data available you insert it into the database.
  • symbols This argument needs to be a list of stock ticker symbols (for example, MSFT) or crypto trading pairs (for example, BTC/USD). When using a websocket connection you always need to subscribe to the events you want to receive. You can do this by using the symbols argument or if your connection is already created you can also use the subscribe() function to get data for additional symbols.
Connect to the websocket server
  1. Create a new Python file called websocket_test.py and connect to the Twelve Data servers using the <YOUR_API_KEY>:
  2. Run the Python script:
  3. When you run the script, you receive a response from the server about the status of your connection:
    When you have established a connection to the websocket server, wait a few seconds, and you can see data records, like this:
    Each price event gives you multiple data points about the given trading pair such as the name of the exchange, and the current price. You can also occasionally see heartbeat events in the response; these events signal the health of the connection over time. At this point the websocket connection is working successfully to pass data.

Optimize time-series data in a hypertable

s are tables in that automatically partition your time-series data by time. Time-series data represents the way a system, process, or behavior changes over time. s enable to work efficiently with time-series data. Each is made up of child tables called chunks. Each chunk is assigned a range of time, and only contains data from that range. When you run a query, identifies the correct chunk and runs the query on it, instead of going through the entire table. is the hybrid row-columnar storage engine in used by s. Traditional databases force a trade-off between fast inserts (row-based storage) and efficient analytics (columnar storage). eliminates this trade-off, allowing real-time analytics without sacrificing transactional capabilities. dynamically stores data in the most efficient format for its lifecycle: Move from rowstore to columstore in hypercore
  • Row-based storage for recent data: the most recent chunk (and possibly more) is always stored in the , ensuring fast inserts, updates, and low-latency single record queries. Additionally, row-based storage is used as a writethrough for inserts and updates to columnar storage.
  • Columnar storage for analytical performance: chunks are automatically compressed into the , optimizing storage efficiency and accelerating analytical queries.
Unlike traditional columnar databases, allows data to be inserted or modified at any stage, making it a flexible solution for both high-ingest transactional workloads and real-time analytics—within a single database. Because is 100% , you can use all the standard tables, indexes, stored procedures, and other objects alongside your s. This makes creating and working with s similar to standard .
  1. Connect to your In open an SQL editor. You can also connect to your service using psql.
  2. Create a to store the real-time cryptocurrency data Create a for your time-series data using CREATE TABLE. For efficient queries on data in the , remember to segmentby the column you will use most often to filter your data:
    When you create a using CREATE TABLE … WITH …, the default partitioning column is automatically the first column with a timestamp data type. Also, creates a columnstore policy that automatically converts your data to the , after an interval equal to the value of the chunk_interval, defined through compress_after in the policy. This columnar format enables fast scanning and aggregation, optimizing performance for analytical workloads while also saving significant storage space. In the conversion, s are compressed by up to 98%, and organized for efficient, large-scale queries. You can customize this policy later using alter_job. However, to change after or created_before, the compression settings, or the the policy is acting on, you must remove the columnstore policy and add a new one. You can also manually convert s in a to the .

Create a standard Postgres table for relational data

When you have relational data that enhances your time-series data, store that data in standard relational tables.
  1. Add a table to store the asset symbol and name in a relational table
You now have two tables within your . A hypertable named crypto_ticks, and a normal table named crypto_assets. When you ingest data into a transactional database like , it is more efficient to insert data in batches rather than inserting data row-by-row. Using one transaction to insert multiple rows can significantly increase the overall ingest capacity and speed of your .

Batching in memory

A common practice to implement batching is to store new records in memory first, then after the batch reaches a certain size, insert all the records from memory into the database in one transaction. The perfect batch size isn’t universal, but you can experiment with different batch sizes (for example, 100, 1000, 10000, and so on) and see which one fits your use case better. Using batching is a fairly common pattern when ingesting data into from Kafka, Kinesis, or websocket connections. To ingest the data into your , you need to implement the on_event function. After the websocket connection is set up, you can use the on_event function to ingest data into the database. This is a data pipeline that ingests real-time financial data into your . You can implement a batching solution in Python with Psycopg2. You can implement the ingestion logic within the on_event function that you can then pass over to the websocket object. This function needs to:
  1. Check if the item is a data item, and not websocket metadata.
  2. Adjust the data so that it fits the database schema, including the data types, and order of columns.
  3. Add it to the in-memory batch, which is a list in Python.
  4. If the batch reaches a certain size, insert the data, and reset or empty the list.

Ingest data in real-time

  1. Update the Python script that prints out the current batch size, so you can follow when data gets ingested from memory into your database. Use the <HOST>, <PASSWORD>, and <PORT> details for the where you want to ingest the data and your API key from Twelve Data:
  2. Run the script:
You can even create separate Python scripts to start multiple websocket connections for different types of symbols, for example, one for stock, and another one for cryptocurrency prices.

Troubleshooting

If you see an error message similar to this:
Then check that you use a proper API key received from Twelve Data.

Query the data

To look at OHLCV values, the most effective way is to create a . You can create a to aggregate data for each day, then set the aggregate to refresh every day, and aggregate the last two days’ worth of data.

Creating a continuous aggregate

  1. Connect to the tsdb that contains the Twelve Data cryptocurrency dataset.
  2. At the psql prompt, create the to aggregate data every day:
    When you create the , it refreshes by default.
  3. Set a refresh policy to update the every day, if there is new data available in the for the last two days:

Query the continuous aggregate

When you have your set up, you can query it to get the OHLCV values.
  1. Connect to the that contains the Twelve Data cryptocurrency dataset.
  2. At the psql prompt, use this query to select all Bitcoin OHLCV data for the past 14 days, by time bucket:
    The result of the query looks like this:

Connect Grafana to Tiger Cloud

To visualize the results of your queries, enable Grafana to read the data in your :
  1. Log in to Grafana In your browser, log in to either:
    • Self-hosted Grafana: at http://localhost:3000/. The default credentials are admin, admin.
    • Grafana Cloud: use the URL and credentials you set when you created your account.
  2. Add your as a data source
    1. Open Connections > Data sources, then click Add new data source.
    2. Select PostgreSQL from the list.
    3. Configure the connection:
      • Host URL, Database name, Username, and Password Configure using your connection details. Host URL is in the format <host>:<port>.
      • TLS/SSL Mode: select require.
      • PostgreSQL options: enable TimescaleDB.
      • Leave the default setting for all other fields.
    4. Click Save & test.
    Grafana checks that your details are set correctly.

Graph OHLCV data

When you have extracted the raw OHLCV data, you can use it to graph the result in a candlestick chart, using Grafana.
  1. In Grafana, from the Dashboards page, click New and select New dashboard.
  2. Click Add visualization, then select the data source that connects to your and the Candlestick visualization type in the top right.
  3. In the Queries section, select Code and paste the query you used to get the OHLCV values:
  4. Adjust elements of the table as required, and click Apply to save your graph to the dashboard. Creating a candlestick graph in Grafana using 1-day OHLCV tick data