Query editor
WITH prices AS (SELECT(SELECT SUM(volume_usd) / SUM(CASEWHEN LOWER(CAST(token_bought_address AS VARCHAR)) = LOWER('0:6ca2c99c66b0fa1478a303ba9618bc39c28fda1fc50de37e618bddf98c9fd24c') THEN amount_bought_raw / 1e9ELSE amount_sold_raw / 1e9END)FROM ton.dex_tradesWHERE (LOWER(CAST(token_bought_address AS VARCHAR)) = LOWER('0:6ca2c99c66b0fa1478a303ba9618bc39c28fda1fc50de37e618bddf98c9fd24c') OR LOWER(CAST(token_sold_address AS VARCHAR)) = LOWER('0:6ca2c99c66b0fa1478a303ba9618bc39c28fda1fc50de37e618bddf98c9fd24c'))AND block_time > NOW() - INTERVAL '1' DAY) as storm_price),storm_update_position AS (SELECT * FROM stormtrade_ton.update_position),storm_complete_order AS (SELECT * FROM stormtrade_ton.complete_order),storm_execute_order AS (SELECT * FROM stormtrade_ton.execute_order),storm_trade_notification AS (SELECT * FROM stormtrade_ton.trade_notification),position_sizes_raw AS (SELECT user_position, sup.direction, sup.position_size, sup.tx_lt as created_lt FROM storm_update_position supUNION ALLSELECT user_position, sco.direction, sco.position_size, sco.tx_lt as created_lt FROM storm_complete_order sco),position_sizes AS (SELECT DISTINCT * FROM position_sizes_raw),prev_position AS (select user_position, direction, created_lt, COALESCE(LAG(position_size, 1) OVER(PARTITION BY user_position, direction ORDER BY created_lt ASC), CAST(0 AS DECIMAL)) as prev_positionfrom position_sizes),positions_raw AS (SELECT DISTINCT stn.trader_addr, sup.user_position, stn.asset_id FROM storm_update_position supJOIN ton.messages notif_message_out ON notif_message_out.block_date = sup.block_date AND notif_message_out.tx_hash = sup.tx_hash AND notif_message_out.direction = 'out'JOIN ton.messages notif_message_in ON notif_message_out.block_date = notif_message_in.block_dateAND notif_message_out.msg_hash = notif_message_in.msg_hash AND notif_message_in.direction = 'in'JOIN storm_trade_notification stn ON stn.tx_hash = sup.tx_hashWHERE sup.origin_op != 3427973859UNION ALLSELECT DISTINCT seo.trader_addr , seo.user_position, seo.oracle_asset_id as asset_id FROM storm_execute_order seo),positions AS (SELECT DISTINCT trader_addr, user_position, MAX(asset_id) as asset_id FROM positions_rawGROUP BY 1, 2),position_open AS (SELECT tx_hash, vault_token, 'open' as event_type, positions.trader_addr, positions.asset_id,tx_lt as created_lt, tx_now, sup.direction, position_size,COALESCE(ABS(prev_position - position_size ) * 1.0 * quote_asset_weight * quote_asset_reserve / NULLIF(base_asset_reserve, 0) / 1e18, position_open_notional / 1e9) as volume,position_feeFROM stormtrade_ton.update_position supJOIN positions ON positions.user_position = sup.user_positionJOIN prev_position pp ON pp.user_position = sup.user_position and pp.direction = sup.direction and pp.created_lt = sup.tx_lt