For AI agents: the complete documentation index is at llms.txt. Every page is also available as markdown by appending .md to its URL, or by sending an Accept: text/markdown request header.

Volume spike detection

Detect volume spikes by comparing current trading volume against the previous candle's volume.

Problem​

You have candles aggregated at 30 seconds intervals, and you want to show a flag 'spike' if volume is bigger than twice the latest record for the same symbol. Otherwise it should display 'normal'.

Solution​

Use the LAG window function to retrieve the previous candle's volume, then compare with a CASE statement:

Detect volume spikes exceeding 2x previous volumeDemo this query
DECLARE
@range := '$now - 7h..$now',
@symbol := 'EURUSD'
WITH candles AS (
SELECT
timestamp,
symbol,
sum(quantity) AS volume
FROM fx_trades
WHERE timestamp IN @range
AND symbol = @symbol
SAMPLE BY 30s
),
prev_volumes AS (
SELECT
timestamp,
symbol,
volume,
LAG(volume) OVER (PARTITION BY symbol ORDER BY timestamp) AS prev_volume
FROM candles
)
SELECT
*,
CASE
WHEN volume > 2 * prev_volume THEN 'spike'
ELSE 'normal'
END AS spike_flag
FROM prev_volumes;