I have a table named trades
for holding currency trading data with the following schema:
id - uuid
timestamp - timestamp without time zone
price - numeric
I would like to be able to query in a way that I can build a candle chart. For this I need the first price, the last price, the max price and the min price, grouped by time intervals. So far I have this:
CREATE FUNCTION ts_round( timestamptz, INT4 ) RETURNS TIMESTAMPTZ AS $$
SELECT 'epoch'::timestamptz
+ '1 second'::INTERVAL * ( $2 * ( extract( epoch FROM $1 )::INT4 / $2 ) );
$$ LANGUAGE SQL;
SELECT ts_round( timestamp, 300 ) AS interval_timestamp
, max(price) AS max, min(price) AS min
FROM trades
GROUP BY interval_timestamp
ORDER BY interval_timestamp DESC
How do I get the first price and last price within these intervals?