Query editor
WITH union_events AS (SELECT trace_id, user_position, direction, tx_lt, tx_now, position_size, position_open_notional, position_margin, amm, oracle_price, settlement_oracle_price, CAST(position_fee AS INT256) AS position_fee, origin_op, 2 AS src_rank, tx_hashFROM stormtrade_ton.update_positionUNION ALLSELECT trace_id, user_position, direction, tx_lt, tx_now, position_size, position_open_notional, position_margin, amm, oracle_price, settlement_oracle_price, CAST(position_fee AS INT256) AS position_fee, origin_op, 1 AS src_rank, tx_hashFROM 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),event_details AS (SELECTe.*,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_size,COALESCE(LAG(e.position_open_notional) OVER (PARTITION BY e.user_position, e.direction ORDER BY e.tx_lt, e.trace_id), CAST(0 AS INT256)) as prev_open_notionalFROM events e)SELECTed.tx_hash AS id,FROM_UNIXTIME(ed.tx_now) AS block_timestamp,ed.tx_now,tn.trader_addr,ed.user_position,CASE WHEN ed.direction = 0 THEN 'long' ELSE 'short' END AS direction,ed.event_type,-- Состояние позицииed.position_size / 1e9 as position_size,ed.position_open_notional / 1e9 as position_notional,ed.position_margin / 1e9 as position_margin,-- Данные транзакцииtn.vault_token AS margin_token,COALESCE(CAST(tn.locked_amount AS INT256), 0) / 1e9 as locked_amount_native,COALESCE(CAST(tn.withdraw_locked_amount AS INT256), 0) / 1e9 as withdraw_amount_native,-- PnL (USD)(CASEWHEN ed.event_type IN ('close_position', 'liquidate', 'max_pnl', 'decrease_or_close')THEN (COALESCE(CAST(tn.withdraw_locked_amount AS INT256), 0) - COALESCE(CAST(tn.locked_amount AS INT256), 0))ELSE 0END / 1e9) * (ed.oracle_price / 1e9) AS pnl_usd,