Candlestick charts are a widely used chart type in stock markets and financial trading, designed to display information such as the opening price, highest price, lowest price, and closing price over a specific time period. This article introduces how to convert real-time tick data into candlestick data of various timeframes and provides essential formulas and calculation methods to help you better analyze and understand market trends.

1. Introduction to Candlestick Charts

Candlestick charts consist of a series of consecutive rectangular bars, each representing price movements within a specific time interval. Each candlestick typically includes four key price points: Opening price (Open), Highest price (High), Lowest price (Low), and Closing price (Close). The shape and patterns of candlesticks can help analysts and traders identify market trends and price patterns.

2. Real-Time Tick Data

Real-time tick data refers to the price and volume information of each transaction in the market. It provides immediate feedback on market liquidity and price changes. A typical tick data record includes fields such as timestamp, transaction price, and transaction volume.

3. Candlestick Data Calculation Method

Time Window Setting
First, you need to define the timeframe of the candlestick chart, such as 1 minute, 15 minutes, 1 hour, etc. This determines the sampling interval from the real-time tick data.

Candlestick Data Calculation
For each time window, calculate the candlestick values based on the tick data:

  • Open: The price of the first tick within the time window
  • High: The highest price within the time window
  • Low: The lowest price within the time window
  • Close: The price of the last tick within the time window

Updating Candlestick Data
As time progresses, each time window shifts, and new tick data comes into scope. At the end of each time window, update the candlestick data using the newly received tick data.

Other Indicator Calculations
In addition to OHLC values, you can also calculate other indicators from candlestick data, such as trading volume and moving averages. These indicators can provide deeper market insights.

4. Example Formulas

Below is an example demonstrating how to convert real-time tick data into 1-minute candlestick data:

  1. Initialize Candlestick Data:
  • Initial Open: The price of the first tick
  • Initial High: The price of the first tick
  • Initial Low: The price of the first tick
  • Initial Close: The price of the first tick
  1. Update Candlestick Data:
  • If the timestamp of the current tick is outside the current time window, it indicates the window has ended, and the candlestick data needs to be updated.
  • New Open: The closing price of the previous time window
  • New High: The highest price within the new time window
  • New Low: The lowest price within the new time window
  • New Close: The price of the current tick

This is a simple example. In real-world applications, more detailed data handling and logic may be required to meet specific needs.

5. Java Code Example

import java.util.ArrayList;
import java.util.List;

public class KLineGenerator {
    public static List<KLineData> generateKLineData(List<TickData> tickDataList, int interval) {
        List<KLineData> kLineDataList = new ArrayList<>();
        long startTime = tickDataList.get(0).getTime(); 


        long currentKLineStartTime = startTime - (startTime % interval);
        double openPrice = tickDataList.get(0).getPrice();
        double highPrice = openPrice;
        double lowPrice = openPrice;
        double closePrice = 0;
        long volume = 0;


        for (TickData tickData : tickDataList) {
            long currentTime = tickData.getTime();
            double currentPrice = tickData.getPrice();
            long currentVolume = tickData.getVolume();


            if (currentTime >= currentKLineStartTime + interval) {
                closePrice = tickDataList.get(tickDataList.indexOf(tickData) - 1).getPrice(); // 上一个Tick的价格作为收盘价

                KLineData kLineData = new KLineData(currentKLineStartTime, openPrice, highPrice, lowPrice, closePrice, volume);
                kLineDataList.add(kLineData);


                currentKLineStartTime += interval;
                openPrice = currentPrice;
                highPrice = currentPrice;
                lowPrice = currentPrice;
                volume = currentVolume;
            } else {

                highPrice = Math.max(highPrice, currentPrice);
                lowPrice = Math.min(lowPrice, currentPrice);
                volume += currentVolume;
            }
        }


        closePrice = tickDataList.get(tickDataList.size() - 1).getPrice();


        KLineData lastKLineData = new KLineData(currentKLineStartTime, openPrice, highPrice, lowPrice, closePrice, volume);
        kLineDataList.add(lastKLineData);

        return kLineDataList;
    }
}


class TickData {
    private long time;
    private double price;
    private long volume;

    public TickData(long time, double price, long volume) {
        this.time = time;
        this.price = price;
        this.volume = volume;
    }

    public long getTime() {
        return time;
    }

    public double getPrice() {
        return price;
    }

    public long getVolume() {
        return volume;
    }
}


class KLineData {
    private long time;
    private double open;
    private double high;
    private double low;
    private double close;
    private long volume;

    public KLineData(long time, double open, double high, double low, double close, long volume) {
        this.time = time;
        this.open = open;
        this.high = high;
        this.low = low;
        this.close = close;
        this.volume = volume;
    }


}

6. Python Code Example

from datetime import datetime, timedelta

class TickData:
    def __init__(self, time, price, volume):
        self.time = time
        self.price = price
        self.volume = volume

class KLineData:
    def __init__(self, time, open_price, high_price, low_price, close_price, volume):
        self.time = time
        self.open_price = open_price
        self.high_price = high_price
        self.low_price = low_price
        self.close_price = close_price
        self.volume = volume

def generate_kline_data(tick_data_list, interval):
    kline_data_list = []
    start_time = tick_data_list[0].time
    current_kline_start_time = start_time - (start_time % interval)
    open_price = tick_data_list[0].price
    high_price = open_price
    low_price = open_price
    close_price = 0
    volume = 0

    for tick_data in tick_data_list:
        current_time = tick_data.time
        current_price = tick_data.price
        current_volume = tick_data.volume

        if current_time >= current_kline_start_time + interval:
            close_price = tick_data_list[tick_data_list.index(tick_data) - 1].price
            kline_data = KLineData(current_kline_start_time, open_price, high_price, low_price, close_price, volume)
            kline_data_list.append(kline_data)

            current_kline_start_time += interval
            open_price = current_price
            high_price = current_price
            low_price = current_price
            volume = current_volume
        else:
            high_price = max(high_price, current_price)
            low_price = min(low_price, current_price)
            volume += current_volume

    close_price = tick_data_list[-1].price
    last_kline_data = KLineData(current_kline_start_time, open_price, high_price, low_price, close_price, volume)
    kline_data_list.append(last_kline_data)

    return kline_data_list