WITH selected_events AS ( SELECT s.market FROM listed_markets s LEFT JOIN augmented_outcomes a ON a.market=s.market WHERE s.event IN (SELECT value FROM json_each(:events)) AND (a.role IS NULL OR a.role<>'placeholder') ), executions AS ( SELECT p.at_ms,p.fill AS execution,p.market,f.bid AS first_order,f.ask AS second_order, f.price,f.quantity,'transfer' AS kind FROM trade_prices p JOIN fills f ON f.seq=p.fill WHERE p.at_ms BETWEEN :start AND :before_ms AND (p.at_ms,p.fill)<=(:before_ms,:before_execution) UNION ALL SELECT at_ms,seq,market,yes_order,no_order,yes_price,quantity,kind FROM paired_fills WHERE at_ms BETWEEN :start AND :before_ms AND (at_ms,seq)<=(:before_ms,:before_execution) ), legs AS ( SELECT e.at_ms,e.execution,e.market,o.seq AS order_seq,o.account,o.outcome,o.side,e.kind, CASE WHEN e.kind<>'transfer' AND o.seq=e.second_order THEN 100-e.price ELSE e.price END AS price, e.quantity, CASE WHEN c.execution IS NULL THEN NULL WHEN c.taker_order IS NULL THEN 'auction' WHEN c.taker_order=o.seq THEN 'taker' ELSE 'maker' END AS role FROM executions e JOIN orders o ON o.seq IN (e.first_order,e.second_order) LEFT JOIN execution_context c ON c.execution=e.execution WHERE (:markets IS NULL OR e.market IN (SELECT value FROM json_each(:markets))) AND (:events IS NULL OR e.market IN (SELECT market FROM selected_events)) AND (:side IS NULL OR o.side=:side) AND (NOT :taker_only OR c.taker_order=o.seq) AND (e.at_ms,e.execution,o.seq)<(:before_ms,:before_execution,:before_order) ) SELECT at_ms,execution,order_seq,account,market,outcome,side,kind,price,quantity,role FROM legs WHERE CASE WHEN :cash THEN price*quantity/100.0 ELSE quantity END >= :minimum ORDER BY at_ms DESC,execution DESC,order_seq DESC LIMIT :limit