Query editor
WITH latest_positions AS (SELECTDATE_TRUNC('day', s.block_date) AS day,s.sender_address AS user,s.pool_name,s.asset_id,LAST_VALUE(s.user_new_principal) OVER (PARTITION BY s.sender_address, s.pool_name, s.asset_id, DATE_TRUNC('day', s.block_date) ORDER BY s.tx_now, s.tx_lt RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS latest_principal,LAST_VALUE(s.s_rate) OVER (PARTITION BY s.sender_address, s.pool_name, s.asset_id, DATE_TRUNC('day', s.block_date) ORDER BY s.tx_now, s.tx_lt RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS latest_s_rate,LAST_VALUE(s.b_rate) OVER (PARTITION BY s.sender_address, s.pool_name, s.asset_id, DATE_TRUNC('day', s.block_date) ORDER BY s.tx_now, s.tx_lt RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS latest_b_rateFROM (SELECTblock_date,tx_hash,tx_now,tx_lt,pool_name,sender_address,asset_id,user_new_principal,s_rate,b_rateFROM evaa_ton.supplyUNION ALLSELECTblock_date,tx_hash,tx_now,tx_lt,pool_name,sender_address,asset_id,user_new_principal,s_rate,b_rateFROM evaa_ton.withdraw) AS s), user_positions_with_prices AS (SELECTlp.day,lp.user,lp.pool_name,a.asset_name,CASEWHEN lp.latest_principal > 0THEN (lp.latest_principal * lp.latest_s_rate / POWER(10, 12)) * p.price_usdWHEN lp.latest_principal < 0THEN ABS(lp.latest_principal * lp.latest_b_rate / POWER(10, 12)) * p.price_usdELSE 0END AS position_usd,CASEWHEN lp.latest_principal > 0THEN 'supply'WHEN lp.latest_principal < 0THEN 'borrow'ELSE 'none'END AS position_typeFROM latest_positions AS lpJOIN evaa_ton.assets AS a