Query editor
WITH union_events 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, 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, 1 AS src_rankFROM stormtrade_ton.complete_order),events_raw AS (SELECT *,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_typeFROM union_events),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),session_event_details AS (SELECTews.*,tn.vault_token AS margin_token,tn.locked_amount,tn.withdraw_locked_amount,tn.executor_amount,LAST_VALUE(ews.position_size) OVER (PARTITION BY ews.user_position, ews.direction, ews.session_id ORDER BY ews.tx_lt, ews.trace_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) = 0 AS is_closed,CASEWHEN ews.event_type NOT IN ('add_margin', 'remove_margin') THEN(CAST(ews.position_fee AS INT256) * (CASEWHEN ews.event_type = 'increase' THEN ABS(ews.position_open_notional - COALESCE(LAG(ews.position_open_notional) OVER (PARTITION BY ews.user_position, ews.direction ORDER BY ews.tx_lt, ews.trace_id), CAST(0 AS INT256)))ELSE (CAST(ABS(ews.position_size - COALESCE(LAG(ews.position_size) OVER (PARTITION BY ews.user_position, ews.direction ORDER BY ews.tx_lt, ews.trace_id), CAST(0 AS INT256))) AS INT256) * ews.oracle_price) / 1000000000END)) / 1e9 / 1e9ELSE 0END AS position_fee_usd_per_eventFROM events_with_sessions ewsLEFT JOIN stormtrade_ton.trade_notification tn ON ews.trace_id = tn.trace_id AND ews.amm = tn.amm),session_details AS (SELECT