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_volume AS (SELECTs.tx_now,s.position_fee,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_rawFROM (SELECTe.*,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 e) s),daily_position_fees AS (SELECTDATE(FROM_UNIXTIME(tx_now)) AS trade_date,SUM((CAST(position_fee AS INT256) * trade_volume_raw) / 1e9) / 1e9 AS daily_position_fee_usdFROM events_with_volumeWHERE trade_volume_raw IS NOT NULLGROUP BY 1),events_with_amounts AS (SELECTe.tx_now,e.trace_id,e.amm,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,COALESCE(CAST(tn.executor_amount AS INT256), 0) AS executor_amount