Query editor
WITH events_raw AS (SELECT trace_id, user_position, direction, tx_lt, tx_now, position_size, position_open_notional, amm, oracle_price, position_fee,CASE WHEN origin_op = 2774268195 THEN 'increase' 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, position_fee,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 er.*,ROW_NUMBER() OVER (PARTITION BY er.trace_id, er.ammORDER BY er.src_rank, er.tx_lt, er.trace_id) AS rnFROM events_raw er) xWHERE x.rn = 1),events_with_amounts AS (SELECTe.user_position, e.direction, e.tx_lt, e.tx_now, e.trace_id, e.event_type, e.position_size, e.position_open_notional, e.amm, e.oracle_price, e.position_fee,(COALESCE(CAST(tn.locked_amount AS INT256), 0) - COALESCE(CAST(tn.withdraw_locked_amount AS INT256), 0)) AS margin_change,COALESCE(CAST(tn.locked_amount AS INT256), 0) AS locked_amount,COALESCE(CAST(tn.withdraw_locked_amount AS INT256), 0) AS withdraw_amount,tn.vault_token AS margin_token,tn.trader_addr,COALESCE(CAST(tn.executor_amount AS INT256), 0) AS executor_amountFROM events eLEFT JOIN stormtrade_ton.trade_notification tn ON e.trace_id = tn.trace_id AND e.amm = tn.amm),events_with_margin AS (SELECTewa.*,SUM(margin_change) OVER (PARTITION BY user_position, direction ORDER BY tx_lt, trace_id) AS current_marginFROM events_with_amounts ewa),events_with_sessions_and_volume AS (SELECTs.*,CASEWHEN s.event_type = 'increase' THEN ABS(s.position_open_notional - s.prev_open_notional)WHEN s.event_type = 'decrease_or_close' THEN (CAST(ABS(s.position_size - s.prev_size) AS INT256) * s.oracle_price) / 1000000000END AS trade_volume_raw,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 (SELECTewm.*,COALESCE(LAG(position_size) OVER (PARTITION BY user_position, direction ORDER BY tx_lt, trace_id), CAST(0 AS INT256)) AS prev_size,COALESCE(LAG(position_open_notional) OVER (PARTITION BY user_position, direction ORDER BY tx_lt, trace_id), CAST(0 AS INT256)) AS prev_open_notionalFROM events_with_margin ewm