Query editor
-- EVM wallet DEX PnL (average-cost analytical estimate)WITH params AS (SELECT from_hex(replace(lower('{{wallet_address}}'),'0x','')) AS wallet),wallet_trades AS (SELECT blockchain, block_time, tx_hash,token_bought_address, token_bought_symbol, token_bought_amount,token_sold_address, token_sold_symbol, token_sold_amount, amount_usdFROM dex.trades CROSS JOIN paramsWHERE taker = walletAND blockchain = '{{blockchain}}'AND block_time >= CAST('{{start_date}}' AS timestamp)AND amount_usd IS NOT NULL),token_legs AS (SELECT blockchain, block_time, tx_hash,token_bought_address AS token_address,coalesce(token_bought_symbol,'UNKNOWN') AS token_symbol,token_bought_amount AS buy_amount, amount_usd AS buy_usd,CAST(0 AS double) AS sell_amount, CAST(0 AS double) AS sell_usdFROM wallet_trades WHERE token_bought_amount > 0UNION ALLSELECT blockchain, block_time, tx_hash,token_sold_address, coalesce(token_sold_symbol,'UNKNOWN'),CAST(0 AS double), CAST(0 AS double), token_sold_amount, amount_usdFROM wallet_trades WHERE token_sold_amount > 0),token_totals AS (SELECT blockchain, token_address, max_by(token_symbol,block_time) AS token_symbol,min(block_time) AS first_trade, max(block_time) AS last_trade,count(DISTINCT tx_hash) AS trade_count,sum(buy_amount) AS bought_amount, sum(buy_usd) AS buy_volume_usd,sum(sell_amount) AS sold_amount, sum(sell_usd) AS sell_volume_usdFROM token_legs GROUP BY 1,2),pnl AS (SELECT t.*,buy_volume_usd/nullif(bought_amount,0) AS avg_buy_price_usd,sell_volume_usd/nullif(sold_amount,0) AS avg_sell_price_usd,greatest(bought_amount-sold_amount,0) AS estimated_open_amount,least(bought_amount,sold_amount) *(sell_volume_usd/nullif(sold_amount,0)-buy_volume_usd/nullif(bought_amount,0)) AS realized_pnl_usd,p.price AS latest_price_usd, p.minute AS price_updated_atFROM token_totals tLEFT JOIN prices.usd_latest pON p.blockchain=t.blockchain AND p.contract_address=t.token_address),valued AS (SELECT *,estimated_open_amount*latest_price_usd AS open_value_usd,estimated_open_amount*(latest_price_usd-avg_buy_price_usd) AS unrealized_pnl_usd,coalesce(realized_pnl_usd,0)+ coalesce(estimated_open_amount*(latest_price_usd-avg_buy_price_usd),0) AS total_pnl_usdFROM pnl)SELECT blockchain, token_symbol, token_address, trade_count, first_trade, last_trade,bought_amount, sold_amount, estimated_open_amount,buy_volume_usd, sell_volume_usd, avg_buy_price_usd, avg_sell_price_usd,coalesce(realized_pnl_usd,0) AS realized_pnl_usd,latest_price_usd, open_value_usd, unrealized_pnl_usd, total_pnl_usd,