Query editor
WITH events_raw AS (SELECT trace_id, user_position, direction, tx_lt, tx_now, position_size, position_open_notional, amm, oracle_price, CAST(position_fee AS INT256) as position_fee, origin_op,CASEWHEN origin_op = 2774268195 THEN 'increase'WHEN origin_op = 3118993634 THEN 'add_margin'WHEN origin_op = 3974026278 THEN 'remove_margin'WHEN origin_op = 1556101853 THEN 'close_position'WHEN origin_op = 3427973859 THEN 'liquidate'WHEN origin_op = 600100713 THEN 'max_pnl'ELSE 'decrease_or_close'END AS event_type,2 AS src_rankFROM stormtrade_ton.update_positionUNION ALLSELECT trace_id, user_position, direction, tx_lt, tx_now, position_size, position_open_notional, amm, oracle_price, CAST(position_fee AS INT256) as position_fee, origin_op,CASE WHEN origin_op = 2774268195 THEN 'increase' ELSE 'decrease_or_close' END AS event_type,1 AS src_rankFROM stormtrade_ton.complete_order),events AS (SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY trace_id, amm ORDER BY src_rank, tx_lt, trace_id) AS rnFROM events_raw) WHERE rn = 1),events_with_sessions AS (SELECT s.*,SUM(CASE WHEN s.prev_size = 0 AND s.position_size <> 0 THEN 1 ELSE 0 END)OVER (PARTITION BY s.user_position, s.direction ORDER BY s.tx_lt, s.trace_id) AS session_idFROM (SELECT e.*,COALESCE(LAG(e.position_size) OVER (PARTITION BY e.user_position, e.direction ORDER BY e.tx_lt, e.trace_id), CAST(0 AS INT256)) AS prev_sizeFROM events e) s),events_with_avg_price AS (SELECT *,CASE WHEN cumulative_size = 0 THEN 0 ELSE cumulative_notional / cumulative_size END AS avg_entry_priceFROM (SELECT *,SUM(CASE WHEN event_type = 'increase' THEN position_size - prev_size ELSE 0 END) OVER (PARTITION BY user_position, direction, session_id ORDER BY tx_lt, trace_id) as cumulative_size,SUM(CASE WHEN event_type = 'increase' THEN (position_size - prev_size) * oracle_price ELSE 0 END) OVER (PARTITION BY user_position, direction, session_id ORDER BY tx_lt, trace_id) as cumulative_notionalFROM events_with_sessions)),events_with_prev_avg_price AS (SELECT *,LAG(avg_entry_price, 1, 0) OVER (PARTITION BY user_position, direction, session_id ORDER BY tx_lt, trace_id) as prev_avg_entry_priceFROM events_with_avg_price),event_details AS (SELECTe.tx_now,tn.vault_token,CASEWHEN e.event_type IN ('close_position', 'liquidate', 'max_pnl', 'decrease_or_close')THEN (e.oracle_price - e.prev_avg_entry_price) * ABS(e.position_size - e.prev_size) / 1e18ELSE 0END AS trading_pnl_native,