Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert tick data to candlestick (OHLC) with SQL

Tags:

sql

mysql

I have a table with columns:

timeInMilliseconds | price

And I want to create OHLC (Open, High, Low, Close) candles from it. That is basically group all the prices from some period of time (let's say every 1 minute) and select the min, max and first and last price of them.

I have created this query so far:

SELECT
  MIN(price) as low,
  MAX(price) as  high,
  FLOOR(timeInMilliseconds/(1000*60)) as open_time
FROM ticks
GROUP BY FLOOR(timeInMilliseconds/(1000*60))

And that works, but the problem is the Open (first) and Close (last) price.
Is there someway to get them in the same query (efficiently)?

like image 639
Enrique Avatar asked Oct 31 '25 16:10

Enrique


1 Answers

You need to find the maximum and minimum times for each time period and then JOIN your table to them to get the price values for those times:

SELECT t1.price AS open,
       m.high,
       m.low,
       t2.price as close,
       open_time
FROM (SELECT MIN(timeInMilliseconds) AS min_time,
             MAX(timeInMilliseconds) AS max_time,
             MIN(price) as low,
             MAX(price) as high,
             FLOOR(timeInMilliseconds/(1000*60)) as open_time
      FROM ticks
      GROUP BY open_time) m
JOIN ticks t1 ON t1.timeInMilliseconds = min_time
JOIN ticks t2 ON t2.timeInMilliseconds = max_time

Demo on dbfiddle

like image 88
Nick Avatar answered Nov 03 '25 08:11

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!