Back to Questdb

Volume spike detection

documentation/cookbook/sql/finance/volume-spike.md

latest1.2 KB
Original Source

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:

questdb-sql
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;

:::info Related Documentation