Real-Time Crypto Risk and Market Surveillance with Streaming SQL: Wash Trading, MEV, Depegs, and On-Chain Monitoring

Real-Time Crypto Risk and Market Surveillance with Streaming SQL: Wash Trading, MEV, Depegs, and On-Chain Monitoring

·

Updated

·

16 min read

Real-time crypto risk and market surveillance with streaming SQL means portfolio value at risk, drawdown, margin utilization, position concentration, wash trading signatures, sandwich attacks, stablecoin peg deviation, and on-chain wallet activity are all maintained as continuously updated materialized views that fire alerts seconds after the price tick, trade, or block that caused them. This guide builds the full surveillance and risk layer on RisingWave, a PostgreSQL-compatible streaming database, for portfolio managers, exchange risk desks, compliance teams, protocol teams, and on-chain analysts.

Why Hourly Risk Is Ancient History in Crypto

Volatility that takes equity markets months to produce arrives in crypto within hours. Markets run 24 hours a day, leverage is high, and venues are interconnected through shared counterparties. Traditional risk systems recompute on a five-minute to overnight cycle, and in that gap a leveraged position passes its margin threshold, a wash trading ring inflates a token into the top movers list, a searcher sandwiches a hundred swaps, or a stablecoin trades at $0.87 for a weekend.

Each of these is detectable from patterns in a stream: a join of positions against latest prices, a self-join of trades within ten minutes, a window function over transaction order within a block, a rolling average of oracle prices against $1.00. RisingWave maintains them as materialized views that update incrementally, so only the affected positions, traders, pools, or addresses are recomputed on each event. RisingWave is open source under Apache 2.0, written in Rust, checkpoints state to S3, and serves results over the PostgreSQL protocol. NOW() in a WHERE clause acts as a temporal filter for rolling windows.

Sources

Risk reads prices and positions. Surveillance reads trades, orders, blocks, oracles, and swaps.

CREATE SOURCE price_feed (
    exchange      VARCHAR,
    trading_pair  VARCHAR,
    asset         VARCHAR,
    price_usd     NUMERIC,
    bid           NUMERIC,
    ask           NUMERIC,
    event_time    TIMESTAMPTZ
) WITH (
    connector = 'kafka',
    topic = 'crypto.market.prices',
    properties.bootstrap.server = 'kafka:9092',
    scan.startup.mode = 'latest'
) FORMAT PLAIN ENCODE JSON;

CREATE TABLE portfolio_positions (
    account_id       VARCHAR,
    asset            VARCHAR,
    quantity         NUMERIC,        -- positive long, negative short
    avg_entry_price  NUMERIC,
    margin_used_usd  NUMERIC,
    leverage         NUMERIC,
    position_time    TIMESTAMPTZ,
    PRIMARY KEY (account_id, asset)
) WITH (
    connector = 'postgres-cdc',
    hostname = 'postgres', port = '5432',
    username = 'replicator', password = 'secret',
    database.name = 'trading_db', schema.name = 'public', table.name = 'positions'
);

CREATE SOURCE trade_events (
    trade_id         VARCHAR,
    exchange         VARCHAR,
    trading_pair     VARCHAR,
    buyer_address    VARCHAR,
    seller_address   VARCHAR,
    maker_trader_id  VARCHAR,
    taker_trader_id  VARCHAR,
    price            NUMERIC,
    quantity         NUMERIC,
    event_time       TIMESTAMPTZ
) WITH (
    connector = 'kafka',
    topic = 'crypto.trades.raw',
    properties.bootstrap.server = 'kafka:9092',
    scan.startup.mode = 'earliest'
) FORMAT PLAIN ENCODE JSON;

CREATE SOURCE block_transactions (
    tx_hash              VARCHAR,
    block_number         BIGINT,
    block_timestamp      TIMESTAMPTZ,
    transaction_index    INTEGER,       -- position within the block
    from_address         VARCHAR,
    to_address           VARCHAR,
    value_eth            NUMERIC,
    gas_price_gwei       NUMERIC,
    gas_used             BIGINT,
    tx_fee_eth           NUMERIC,
    input_function_sig   VARCHAR,
    is_contract_call     BOOLEAN,
    is_contract_create   BOOLEAN,
    is_swap              BOOLEAN,
    token_in             VARCHAR,
    token_out            VARCHAR,
    amount_in            NUMERIC,
    amount_out           NUMERIC,
    status               SMALLINT       -- 1 success, 0 reverted
) WITH (
    connector = 'kafka',
    topic = 'blockchain.blocks.transactions',
    properties.bootstrap.server = 'kafka:9092',
    scan.startup.mode = 'earliest'
) FORMAT PLAIN ENCODE JSON;

CREATE SOURCE oracle_prices (
    token_address  VARCHAR,
    price_usd      NUMERIC,
    source         VARCHAR,          -- 'chainlink', 'pyth', 'band'
    block_ts       TIMESTAMPTZ
) WITH (
    connector = 'kafka',
    topic = 'oracle.price.updates',
    properties.bootstrap.server = 'kafka:9092'
) FORMAT PLAIN ENCODE JSON;

Portfolio Risk: Valuation, Exposure, Volatility, Margin, and Drawdown

The latest price per asset is a DISTINCT ON. Joining it to positions from the trading database through CDC gives live valuation and unrealized P&L; aggregating per account gives exposure, leverage, and margin; a rolling volatility view supplies the input to a parametric VaR estimate.

CREATE MATERIALIZED VIEW latest_prices AS
SELECT DISTINCT ON (asset) asset, price_usd, bid, ask, event_time
FROM price_feed
ORDER BY asset, event_time DESC;

CREATE MATERIALIZED VIEW portfolio_pnl AS
SELECT p.account_id, p.asset, p.quantity, p.avg_entry_price,
       lp.price_usd                                              AS current_price,
       p.quantity * lp.price_usd                                 AS market_value_usd,
       p.quantity * (lp.price_usd - p.avg_entry_price)           AS unrealized_pnl,
       (lp.price_usd - p.avg_entry_price) / NULLIF(p.avg_entry_price, 0) * 100 AS pnl_pct,
       p.margin_used_usd, p.leverage,
       lp.event_time                                             AS price_as_of
FROM portfolio_positions p
JOIN latest_prices lp USING (asset);

CREATE MATERIALIZED VIEW account_risk_summary AS
SELECT account_id,
       SUM(market_value_usd)      FILTER (WHERE quantity > 0)   AS long_exposure_usd,
       SUM(ABS(market_value_usd)) FILTER (WHERE quantity < 0)   AS short_exposure_usd,
       SUM(market_value_usd)                                    AS net_exposure_usd,
       SUM(unrealized_pnl)                                      AS total_unrealized_pnl,
       SUM(margin_used_usd)                                     AS total_margin_used,
       SUM(ABS(market_value_usd)) / NULLIF(SUM(margin_used_usd), 0) AS leverage_ratio,
       COUNT(DISTINCT asset)                                    AS position_count,
       MAX(price_as_of)                                         AS last_updated
FROM portfolio_pnl
GROUP BY account_id;

CREATE MATERIALIZED VIEW asset_volatility_1h AS
SELECT asset, window_start, window_end,
       STDDEV(price_usd)                              AS price_stddev,
       STDDEV(price_usd) / NULLIF(AVG(price_usd), 0)  AS coefficient_of_variation,
       MAX(price_usd) - MIN(price_usd)                AS price_range,
       COUNT(*)                                       AS sample_count
FROM TUMBLE(price_feed, event_time, INTERVAL '1 HOUR')
GROUP BY asset, window_start, window_end;

A simple parametric VaR per position is market value times the asset's coefficient of variation times a z-score (1.65 for 95 percent); summing across positions ignores correlation, which breaks down in stress, so treat it as a first approximation. Alerts come from the account summary and the per-position P&L:

CREATE MATERIALIZED VIEW margin_alerts AS
SELECT account_id, leverage_ratio, total_margin_used, net_exposure_usd, total_unrealized_pnl, last_updated,
       CASE WHEN leverage_ratio >= 10 THEN 'MARGIN_CALL_RISK'
            WHEN leverage_ratio >= 8  THEN 'HIGH_LEVERAGE'
            ELSE 'ELEVATED_LEVERAGE' END AS alert_level
FROM account_risk_summary
WHERE leverage_ratio >= 6;

CREATE MATERIALIZED VIEW drawdown_alerts AS
SELECT account_id, asset, quantity, avg_entry_price, current_price, market_value_usd, unrealized_pnl, pnl_pct, price_as_of
FROM portfolio_pnl
WHERE pnl_pct < -20;

Exchange Risk: Margin Utilization, Concentration, and Liquidation Warnings

An exchange sees the same problem from the other side, across every trader. Positions are built from fills, margin utilization per trader is compared against thresholds, and concentration measures how much of a market's open interest one counterparty holds, because unwinding a 30 percent position moves the market.

CREATE SOURCE trade_fills (
    trade_id         VARCHAR,
    trader_id        VARCHAR,
    instrument_id    VARCHAR,       -- 'BTC-PERP', 'ETH-USD'
    side             VARCHAR,
    quantity         NUMERIC,
    price            NUMERIC,
    notional_usd     NUMERIC,
    leverage         NUMERIC,
    margin_used_usd  NUMERIC,
    fill_ts          TIMESTAMPTZ
) WITH (
    connector = 'kafka',
    topic = 'exchange.trade.fills',
    properties.bootstrap.server = 'kafka:9092'
) FORMAT PLAIN ENCODE JSON;

CREATE MATERIALIZED VIEW trader_positions AS
SELECT trader_id, instrument_id,
       SUM(CASE WHEN side = 'BUY' THEN quantity ELSE -quantity END)  AS net_quantity,
       SUM(notional_usd)                                              AS gross_notional_usd,
       SUM(margin_used_usd)                                           AS margin_used_usd,
       AVG(leverage)                                                  AS avg_leverage,
       MAX(fill_ts)                                                   AS last_trade_ts
FROM trade_fills
GROUP BY trader_id, instrument_id;

CREATE MATERIALIZED VIEW trader_margin_utilization AS
SELECT trader_id,
       SUM(margin_used_usd)                                                             AS total_margin_used,
       SUM(gross_notional_usd)                                                          AS total_notional,
       SUM(margin_used_usd) / NULLIF(SUM(gross_notional_usd / NULLIF(avg_leverage, 0)), 0) * 100 AS margin_utilization_pct,
       COUNT(DISTINCT instrument_id)                                                    AS instrument_count
FROM trader_positions
WHERE net_quantity <> 0
GROUP BY trader_id;

CREATE MATERIALIZED VIEW market_concentration AS
SELECT instrument_id, trader_id, ABS(net_quantity) AS abs_position,
       SUM(ABS(net_quantity)) OVER (PARTITION BY instrument_id) AS market_total_oi,
       ABS(net_quantity) / NULLIF(SUM(ABS(net_quantity)) OVER (PARTITION BY instrument_id), 0) * 100 AS concentration_pct
FROM trader_positions
WHERE net_quantity <> 0;

CREATE MATERIALIZED VIEW exchange_risk_alerts AS
SELECT trader_id, total_margin_used, total_notional, margin_utilization_pct,
       CASE WHEN margin_utilization_pct >= 90 THEN 'LIQUIDATION_WARNING'
            WHEN margin_utilization_pct >= 80 THEN 'MARGIN_CALL'
            ELSE 'ELEVATED_RISK' END AS risk_status
FROM trader_margin_utilization
WHERE margin_utilization_pct >= 70;

CREATE MATERIALIZED VIEW concentration_alerts AS
SELECT instrument_id, trader_id, concentration_pct, abs_position, market_total_oi,
       CASE WHEN concentration_pct >= 30 THEN 'HIGH_CONCENTRATION' ELSE 'MODERATE_CONCENTRATION' END AS alert_type
FROM market_concentration
WHERE concentration_pct >= 15;

In production, margin utilization should be marked to the latest mark price rather than fill price, which is the same latest_prices join used for portfolio risk. Settlement risk peaks in the hours before contract expiry and funding; a filter on last_trade_ts and open interest near those timestamps turns this view into a pre-settlement watchlist.

Wash Trading and Spoofing Surveillance

Wash trading, the same entity buying and selling to itself to inflate volume, distorts every metric market participants rely on and is a compliance obligation for exchanges. Three signatures are detectable from the trade and order streams.

Round trips: two addresses trading back and forth within ten minutes at nearly equal quantity and price.

CREATE MATERIALIZED VIEW round_trip_candidates AS
SELECT t1.exchange, t1.trading_pair,
       t1.buyer_address AS address_a, t1.seller_address AS address_b,
       t1.trade_id AS trade_id_1, t2.trade_id AS trade_id_2,
       t1.quantity AS quantity_1, t2.quantity AS quantity_2,
       ABS(t1.price - t2.price) / NULLIF(t1.price, 0)  AS price_deviation,
       t2.event_time - t1.event_time                    AS round_trip_duration,
       t1.event_time                                    AS first_trade_time
FROM trade_events t1
JOIN trade_events t2
  ON t1.buyer_address  = t2.seller_address
 AND t1.seller_address = t2.buyer_address
 AND t1.trading_pair   = t2.trading_pair
 AND t1.exchange       = t2.exchange
 AND t2.event_time     > t1.event_time
 AND t2.event_time    <= t1.event_time + INTERVAL '10 MINUTES'
 AND ABS(t1.quantity - t2.quantity) / NULLIF(t1.quantity, 0) < 0.05;

Volume concentration: one address producing more than 40 percent of a pair's hourly volume. And self-trades, where the matching engine reports the same trader as maker and taker, plus a high cancel ratio that marks spoofing:

CREATE MATERIALIZED VIEW volume_concentration AS
SELECT exchange, trading_pair, window_start, buyer_address AS address,
       SUM(quantity) AS address_volume,
       SUM(quantity) / NULLIF(SUM(SUM(quantity)) OVER (PARTITION BY exchange, trading_pair, window_start), 0) * 100 AS volume_share_pct
FROM TUMBLE(trade_events, event_time, INTERVAL '1 HOUR')
GROUP BY exchange, trading_pair, window_start, buyer_address;

CREATE MATERIALIZED VIEW self_trade_candidates AS
SELECT window_start, window_end, trading_pair, maker_trader_id,
       COUNT(*) FILTER (WHERE maker_trader_id = taker_trader_id)        AS self_trades,
       COUNT(*)                                                          AS total_trades,
       SUM(quantity) FILTER (WHERE maker_trader_id = taker_trader_id)    AS self_trade_volume
FROM TUMBLE(trade_events, event_time, INTERVAL '5 MINUTES')
GROUP BY window_start, window_end, trading_pair, maker_trader_id
HAVING COUNT(*) FILTER (WHERE maker_trader_id = taker_trader_id) > 0;

CREATE MATERIALIZED VIEW wash_trading_flags AS
SELECT exchange, trading_pair, window_start, address, address_volume, ROUND(volume_share_pct, 2) AS metric,
       'HIGH_VOLUME_CONCENTRATION' AS flag_type
FROM volume_concentration
WHERE volume_share_pct > 40
UNION ALL
SELECT exchange, trading_pair, DATE_TRUNC('hour', first_trade_time), address_a, quantity_1, price_deviation * 100,
       'ROUND_TRIP_DETECTED'
FROM round_trip_candidates
WHERE price_deviation < 0.002;

A cancel ratio view over order_events (orders cancelled divided by orders placed per trader per five minutes, with more than ten placements) completes the picture: a trader who places large orders and cancels 95 percent of them is painting the book. Flagged volume can be excluded from official metrics automatically by anti-joining the flags against the volume views, which is the real payoff of detecting it in real time rather than in a daily report.

MEV: Sandwich Attack Detection

Maximal extractable value is captured by searchers who reorder, insert, or censor transactions within a block. A sandwich is an attacker buy immediately before a victim's swap and an attacker sell immediately after, on the same pair in the same block, with the attacker paying more gas to secure position. Window functions over transaction index within a block expose it:

CREATE MATERIALIZED VIEW block_swap_sequences AS
SELECT block_number, block_timestamp, tx_hash, transaction_index, from_address, token_in, token_out, amount_in, gas_price_gwei,
       amount_out / NULLIF(amount_in, 0)          AS execution_price,
       LAG(tx_hash)         OVER w                AS prev_tx_hash,
       LAG(from_address)    OVER w                AS prev_from,
       LAG(gas_price_gwei)  OVER w                AS prev_gas_price,
       LEAD(tx_hash)        OVER w                AS next_tx_hash,
       LEAD(from_address)   OVER w                AS next_from,
       LEAD(gas_price_gwei) OVER w                AS next_gas_price,
       LEAD(token_in)       OVER w                AS next_token_in,
       LEAD(token_out)      OVER w                AS next_token_out
FROM block_transactions
WHERE is_swap
WINDOW w AS (PARTITION BY block_number, token_in, token_out ORDER BY transaction_index);

CREATE MATERIALIZED VIEW sandwich_attacks AS
SELECT block_number, block_timestamp,
       tx_hash AS victim_tx, from_address AS victim_address,
       prev_tx_hash AS frontrun_tx, prev_from AS attacker_address, next_tx_hash AS backrun_tx,
       token_in, token_out, amount_in AS victim_amount_in, execution_price AS victim_execution_price,
       prev_gas_price AS frontrun_gas_price, gas_price_gwei AS victim_gas_price
FROM block_swap_sequences
WHERE prev_from = next_from                 -- same actor before and after
  AND prev_from <> from_address             -- not the victim
  AND prev_gas_price > gas_price_gwei       -- paid up for position
  AND next_token_in = token_out             -- reverses the trade
  AND next_token_out = token_in;

CREATE MATERIALIZED VIEW top_mev_searchers AS
SELECT attacker_address, COUNT(*) AS sandwich_count, COUNT(DISTINCT block_number) AS active_blocks, MAX(block_timestamp) AS last_seen
FROM sandwich_attacks
GROUP BY attacker_address;

The partition by block and token pair is deliberate: the three legs of a sandwich are adjacent within the pair's ordering even if unrelated transactions sit between them in the block. Protocol teams use the per-block summary to quantify MEV leakage; users get an explanation for why a swap executed at an unexpected price.

Stablecoin Depeg Detection

Stablecoins lose their peg quietly at first. TerraUSD took under 72 hours; USDC traded at $0.87 over the Silicon Valley Bank weekend. A polling monitor that checks oracle prices every minute is three blocks late. A standing query over oracle updates and DEX swaps catches a 0.3 percent deviation within a second.

CREATE MATERIALIZED VIEW stablecoin_prices AS
SELECT token_address,
       AVG(price_usd)                       AS avg_price,
       MIN(price_usd)                       AS min_price,
       MAX(price_usd)                       AS max_price,
       STDDEV(price_usd)                    AS price_stddev,
       COUNT(*)                             AS oracle_count,
       MAX(block_ts)                        AS last_updated,
       ABS(AVG(price_usd) - 1.0) * 100      AS peg_deviation_pct
FROM oracle_prices
WHERE block_ts > NOW() - INTERVAL '1 MINUTE'
GROUP BY token_address;

CREATE TABLE known_stables (token_address VARCHAR PRIMARY KEY, symbol VARCHAR);
INSERT INTO known_stables VALUES
    ('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', 'USDC'),
    ('0xdAC17F958D2ee523a2206206994597C13D831ec7', 'USDT'),
    ('0x6B175474E89094C44Da98b954EedeAC495271d0F', 'DAI');

CREATE MATERIALIZED VIEW depeg_alerts AS
SELECT p.token_address, ks.symbol, p.avg_price, p.peg_deviation_pct, p.oracle_count, p.last_updated,
       CASE WHEN p.peg_deviation_pct >= 5.0 THEN 'CRITICAL'
            WHEN p.peg_deviation_pct >= 2.0 THEN 'HIGH'
            WHEN p.peg_deviation_pct >= 0.5 THEN 'MEDIUM'
            ELSE 'LOW' END                                  AS severity,
       CASE WHEN p.avg_price < 1.0 THEN 'DEPEG_BELOW' ELSE 'DEPEG_ABOVE' END AS direction
FROM stablecoin_prices p
JOIN known_stables ks USING (token_address)
WHERE p.peg_deviation_pct >= 0.3;

Oracle divergence is one of three signals. DEX spot price from swap events on Curve or Uniswap, filtered to swaps above a dust threshold, confirms whether the market agrees with the oracle, and for algorithmic or partially backed coins a reserve ratio from the protocol's own events is the third. Alerting when two of the three agree cuts false positives from a single lagging oracle.

On-Chain Monitoring: Addresses, Gas, Large Transfers, and Watchlists

The chain is public but noisy. Security teams watch for large unexpected transfers from hot wallets, compliance teams track interactions with flagged addresses, and gas analytics warn of congestion before it hurts time-sensitive operations.

CREATE MATERIALIZED VIEW address_activity_24h AS
SELECT from_address, window_start, window_end,
       COUNT(*)                                       AS tx_count,
       COUNT(*) FILTER (WHERE is_contract_call)       AS contract_calls,
       COUNT(*) FILTER (WHERE is_contract_create)     AS contracts_deployed,
       SUM(value_eth)                                 AS total_eth_sent,
       SUM(tx_fee_eth)                                AS total_fees_paid,
       COUNT(*) FILTER (WHERE status = 0)             AS failed_tx_count,
       MAX(block_timestamp)                           AS last_active
FROM HOP(block_transactions, block_timestamp, INTERVAL '1 HOUR', INTERVAL '24 HOURS')
GROUP BY from_address, window_start, window_end;

CREATE MATERIALIZED VIEW block_gas_stats AS
SELECT block_number, MIN(block_timestamp) AS block_time, COUNT(*) AS tx_count,
       AVG(gas_price_gwei)                                              AS avg_gas_price_gwei,
       PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY gas_price_gwei)      AS median_gas_price_gwei,
       SUM(gas_used)                                                    AS total_gas_used,
       COUNT(*) FILTER (WHERE status = 0)                               AS failed_tx_count
FROM block_transactions
GROUP BY block_number;

CREATE MATERIALIZED VIEW gas_spike_alerts AS
SELECT cb.block_number, cb.avg_gas_price_gwei AS current_avg_gwei, b.avg_gas_price_gwei AS baseline_avg_gwei,
       cb.avg_gas_price_gwei / NULLIF(b.avg_gas_price_gwei, 0) AS spike_ratio
FROM block_gas_stats cb
CROSS JOIN (SELECT AVG(avg_gas_price_gwei) AS avg_gas_price_gwei FROM block_gas_stats WHERE block_time >= NOW() - INTERVAL '10 MINUTES') b
WHERE cb.block_time >= NOW() - INTERVAL '1 MINUTE'
  AND cb.avg_gas_price_gwei > b.avg_gas_price_gwei * 3;

CREATE TABLE watchlist (address VARCHAR PRIMARY KEY, label VARCHAR);

CREATE MATERIALIZED VIEW watched_address_alerts AS
SELECT t.tx_hash, t.block_number, t.block_timestamp, t.from_address, t.to_address, t.value_eth, t.input_function_sig, w.label
FROM block_transactions t
JOIN watchlist w ON t.from_address = w.address OR t.to_address = w.address;

CREATE MATERIALIZED VIEW large_transfers AS
SELECT tx_hash, block_number, block_timestamp, from_address, to_address, value_eth
FROM block_transactions
WHERE value_eth >= 100.0 AND status = 1;

The watchlist is a table compliance maintains, so adding a mixer contract or a flagged deployer is an INSERT and every subsequent block is checked against it.

Routing Alerts

Each alert view sinks to Kafka for the team that owns it: risk alerts to the portfolio and exchange risk desks, surveillance flags to compliance, MEV events to protocol teams and researchers, depeg alerts to treasury, on-chain alerts to security.

CREATE SINK risk_alerts_sink AS
SELECT account_id, alert_level, leverage_ratio, last_updated, 'MARGIN' AS risk_type FROM margin_alerts
UNION ALL
SELECT account_id, 'DRAWDOWN', pnl_pct, price_as_of, 'DRAWDOWN' FROM drawdown_alerts
WITH (connector = 'kafka', topic = 'portfolio.alerts.risk', properties.bootstrap.server = 'kafka:9092')
FORMAT PLAIN ENCODE JSON;

CREATE SINK exchange_risk_sink FROM exchange_risk_alerts
WITH (connector = 'kafka', topic = 'exchange.risk.alerts', properties.bootstrap.server = 'kafka:9092')
FORMAT PLAIN ENCODE JSON;

CREATE SINK wash_trading_sink FROM wash_trading_flags
WITH (connector = 'kafka', topic = 'crypto.surveillance.wash-trading', properties.bootstrap.server = 'kafka:9092')
FORMAT PLAIN ENCODE JSON;

CREATE SINK mev_events_sink AS
SELECT block_number, block_timestamp, victim_tx, victim_address, frontrun_tx, attacker_address, token_in, token_out, 'SANDWICH' AS mev_type
FROM sandwich_attacks
WITH (connector = 'kafka', topic = 'blockchain.mev.events', properties.bootstrap.server = 'kafka:9092')
FORMAT PLAIN ENCODE JSON;

CREATE SINK depeg_alert_sink FROM depeg_alerts
WITH (connector = 'kafka', topic = 'alerts.stablecoin.depeg', properties.bootstrap.server = 'kafka:9092')
FORMAT PLAIN ENCODE JSON;

CREATE SINK onchain_alerts_sink AS
SELECT tx_hash, block_number, block_timestamp, from_address, to_address, value_eth, 'LARGE_TRANSFER' AS alert_type FROM large_transfers
UNION ALL
SELECT tx_hash, block_number, block_timestamp, from_address, to_address, value_eth, 'WATCHED_ADDRESS' FROM watched_address_alerts
WITH (connector = 'kafka', topic = 'blockchain.alerts.transactions', properties.bootstrap.server = 'kafka:9092')
FORMAT PLAIN ENCODE JSON;

Risk officers and analysts also query the views directly over PostgreSQL: the top 20 accounts by leverage, the most active round-trip pairs in the last hour, the top searchers by sandwich count, every stablecoin's current deviation.

Batch Cycles vs Streaming SQL for Crypto Risk and Surveillance

ConcernBatch cycleConsequenceStreaming SQL (RisingWave)
Margin and liquidation5 to 15 minutesPosition breaches threshold unseenRecomputed per price tick for affected accounts
ConcentrationEnd of dayOutsized unwind riskWindow function over live positions
Wash tradingDaily reportManipulated volume already in rankingsRound trips and concentration flagged within the hour, excluded from metrics
Sandwich attacksPost-hoc researchLeakage unquantifiedDetected per block via LAG and LEAD
DepegMinute pollingArbitrage window closed0.3 percent deviation within a second
On-chain watchlistExplorer indexing lagMinutes lateJoin per block against a compliance-owned table

Frequently Asked Questions

How should VaR be computed beyond the per-position approximation? Sink asset_volatility_1h and portfolio_pnl to a service that maintains a correlation matrix and runs historical or Monte Carlo VaR, or use a Python user-defined function inside RisingWave for a parametric calculation that includes covariance. The streaming views keep the inputs current; the statistical model is a choice.

Can the wash trading views run on DEX data where there are no trader IDs? Yes. Round trips and volume concentration use wallet addresses, which DEX swaps carry. Self-trade detection needs maker and taker identities and applies to centralized venues.

How do I avoid flagging legitimate market makers as wash traders? Maintain a table of registered market maker accounts and anti-join it from wash_trading_flags, or raise thresholds for those accounts. Price deviation under 0.2 percent on round trips is the discriminating signal; market makers quoting both sides rarely trade with themselves at identical prices.

Does sandwich detection need mempool data? Not for confirmed sandwiches. Block position and gas price are enough once the block is final. Mempool data lets you detect attempts and warn users before execution, which is a separate pending-transaction source feeding the same pattern.

How are reorgs handled for on-chain views? Publish block events with a finality flag or wait for a confirmation depth at the indexer before sending to Kafka. For views that must reflect finalized state only, filter on that flag; for low-latency alerts, accept the small chance of a reorg and mark alerts as provisional until confirmed.

The engine for real-time streaming data.
Analyze, search, and decide.
GitHubXLinkedInSlackYouTube
Sign up for our to stay updated.