Query editor
with buy as (select taker, sum(token_bought_amount)*0.95 as token_bought_amount, sum(amount_usd) as amount_bought_usdfrom dex.tradeswhere token_bought_address = 0xAAB0EaEe80c5e561fe057c243259BA8c31Cd1cCEgroup by 1),sale as (select tx_from as taker, sum(token_sold_amount)/0.95 as token_sold_amount, sum(amount_usd) as amount_sold_usdfrom dex.tradeswhere token_sold_address = 0xAAB0EaEe80c5e561fe057c243259BA8c31Cd1cCEand (token_sold_amount < 9990 or token_sold_amount > 10005)group by 1),presale as (select "to" as users,amount as presale_amount,amount*0.0000020814*1650 as presale_spent_usdfrom tokens_ethereum.transferswhere tx_hash = 0x45a4533a1da9c7f5dcb4d37ac06fe691f61337cab44bba6b09b9ad21f96af0b8and contract_address = 0xaab0eaee80c5e561fe057c243259ba8c31cd1cce and "to" <> 0xa5025faba6e70b84f74e9b1113e5f7f4e7f4859f),price as (select timestamp,pricefrom prices.daywhere contract_address = 0xAAB0EaEe80c5e561fe057c243259BA8c31Cd1cCEorder by 1 desclimit 1),fifo_calc as (selectpresale.users,coalesce(sale.token_sold_amount,0) as token_sold_amount,coalesce(sale.amount_sold_usd,0) as amount_sold_usd,presale.presale_amount,presale.presale_spent_usd,-- Cumulative tokens sold (FIFO)sum(coalesce(sale.token_sold_amount,0)) over (partition by sale.taker order by sale.taker) as cumulative_sold,-- Remaining presale tokenscasewhen sum(coalesce(sale.token_sold_amount,0)) over (partition by sale.taker order by sale.taker) <= presale.presale_amountthen presale.presale_amount - sum(coalesce(sale.token_sold_amount,0)) over (partition by sale.taker order by sale.taker)else 0end as presale_amount_remain,-- Presale tokens sold (FIFO logic)casewhen sum(coalesce(sale.token_sold_amount,0)) over (partition by sale.taker order by sale.taker) <= presale.presale_amountthen sale.token_sold_amountelse least(presale.presale_amount, coalesce(sale.token_sold_amount,0))end as presale_soldfrom presaleleft join sale on presale.users = sale.taker),