Query editor
WITH reg AS (SELECT token_address FROM query_8223393),touch AS (SELECT DISTINCT d.block_date,d.block_number,d.tx_hash,d.token_bought_address AS stock_addressFROM dex.trades dWHERE d.blockchain='bnb'AND d.block_month>=DATE_TRUNC('month',CURRENT_DATE-INTERVAL '30' DAY)AND d.block_date>=CURRENT_DATE-INTERVAL '30' DAY AND d.block_date<CURRENT_DATEAND d.token_bought_address IN (SELECT token_address FROM reg)UNIONSELECT DISTINCT d.block_date,d.block_number,d.tx_hash,d.token_sold_address AS stock_addressFROM dex.trades dWHERE d.blockchain='bnb'AND d.block_month>=DATE_TRUNC('month',CURRENT_DATE-INTERVAL '30' DAY)AND d.block_date>=CURRENT_DATE-INTERVAL '30' DAY AND d.block_date<CURRENT_DATEAND d.token_sold_address IN (SELECT token_address FROM reg)),target_txs AS (SELECT DISTINCT block_date,block_number,tx_hash FROM touch),all_legs AS (SELECT d.block_date,d.block_number,d.tx_hash,d.evt_index,d.token_sold_address,d.token_bought_address,d.amount_usd,CASE WHEN d.project='native' THEN 'Native / RFQ'WHEN d.project='tessera_v' THEN 'Tessera v'||d.versionELSE d.project||' v'||d.version END AS execution_venueFROM dex.trades d JOIN target_txs tON t.block_date=d.block_date AND t.tx_hash=d.tx_hashWHERE d.blockchain='bnb'AND d.block_month>=DATE_TRUNC('month',CURRENT_DATE-INTERVAL '30' DAY)AND d.block_date>=CURRENT_DATE-INTERVAL '30' DAY AND d.block_date<CURRENT_DATE),cycles AS (SELECT block_date,block_number,tx_hashFROM all_legs GROUP BY 1,2,3HAVING count(*)>=2AND min_by(token_sold_address,COALESCE(evt_index,0))=max_by(token_bought_address,COALESCE(evt_index,0))),indexed_touch AS (SELECT t.*,x.index AS tx_indexFROM touch t JOIN bnb.transactions xON x.block_date=t.block_date AND x.hash=t.tx_hashWHERE x.block_date>=CURRENT_DATE-INTERVAL '30' DAY AND x.block_date<CURRENT_DATE),candidate AS (SELECT c.*,it.stock_address,it.tx_index AS arb_indexFROM cycles c JOIN indexed_touch itON it.block_date=c.block_date AND it.tx_hash=c.tx_hash),matches AS (SELECT c.block_date,c.tx_hash,c.arb_index-v.tx_index AS tx_gap,row_number() OVER(PARTITION BY c.tx_hash ORDER BY v.tx_index DESC) AS rnFROM candidate c JOIN indexed_touch vON v.block_number=c.block_number AND v.stock_address=c.stock_addressAND v.tx_hash<>c.tx_hash AND v.tx_index<c.arb_indexAND c.arb_index-v.tx_index<=5),detected AS (SELECT block_date,tx_hash,tx_gap FROM matches WHERE rn=1),detected_legs AS (SELECT d.block_date,d.tx_hash,d.tx_gap,l.execution_venue,l.amount_usdFROM detected d JOIN all_legs l