Query editor
-------------------------------------------------------------------------------------------------- Calculate PnL of Open Trades ---- TODO-- * Fees not incorporated in PnL calculations-- * PnL gets buggy when trader removes a lot of collateral when they're winning-------------------------------------------------------------------------------------------------- Formats trades human-readable-- Numbers trades according to user, side, and tokenwith trades_tmp as (SELECT trades.time, account, ROUND(price,8) as price, key,(CASE indexTokenWHEN 0x82af49447d8a07e3bd95bd0d56f35241523fbab1 THEN 'WETH'WHEN 0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f THEN 'WBTC'WHEN 0xf97f4df75117a78c1a5a0dbb814af92458539fb4 THEN 'LINK'WHEN 0xfa7f8980b0f1e64a2062791cc3b0871572f1f7f0 THEN 'UNI'-- ELSE CONCAT('0x',substring(`data` FROM 91 FOR 40))END) as token,position_side,IF(position_side = 'LONG', ROUND(size,8), 0) as long_size,IF(position_side = 'SHORT', ROUND(size,8), 0) as short_size,ROUND(SUM(size) OVER (PARTITION BY key ORDER BY trades.time),7) as running_total_size, fee,-- ROUND(SUM(size) OVER (PARTITION BY account, trades.indexToken, position_side ORDER BY trades.time),7) as running_total_size,collatDelta,ROW_NUMBER() OVER (PARTITION BY key ORDER BY indexToken, time) as id-- ROW_NUMBER() OVER (PARTITION BY account, trades.indexToken, position_side ORDER BY indexToken, time) as idFROM (-- There are missing txns (eg. 0x774450ccb7892791d32dc757852363e160e05fc48422021c891aa4ce2e8cae61)SELECT evt_block_time as time, key, account, indexToken, price/1e30 as price, sizeDelta/1e30 as size, if(isLong, 'LONG', 'SHORT') as position_side, collateralDelta/1e30 as collatDelta, fee/1e30 as feeFROM gmx_arbitrum.Vault_evt_IncreasePositionWHERE account = {{address}}UNION ALLSELECT evt_block_time as time, key, account, indexToken, markPrice/1e30 as price, -(size/1e30) as size, if(isLong, 'LONG', 'SHORT') as position_side, NULL as collatDelta, 0 as feeFROM gmx_arbitrum.Vault_evt_LiquidatePositionWHERE account = {{address}}UNION ALLSELECT evt_block_time as time, key, account, indexToken, price/1e30 as price, -(sizeDelta/1e30) as size, if(isLong, 'LONG', 'SHORT') as position_side, -(collateralDelta/1e30) as collatDelta, fee/1e30 as feeFROM gmx_arbitrum.Vault_evt_DecreasePositionWHERE account = {{address}}) as trades-- WHERE account = '0xb5beb7b5aa8430a43a516d583e498ce1788446b9' -- DEBUGORDER BY id desc),-- Group trades togethertrades_tmp2 as (SELECT tt.*,COUNT(CASE WHEN running_total_size > 0 THEN NULL ELSE 1 END) OVER (PARTITION BY key ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) as grpFROM trades_tmp ttORDER BY id),-- Calculate running_collat, running_qty-- Flag open/closed trades-- Append recent pricetrades_tmp3 as (SELECT tt2.time, tt2.key, tt2.account, tt2.price, tt2.token, tt2.position_side, tt2.id, tt2.long_size, tt2.short_size, tt2.running_total_size, tt2.collatDelta,SUM(tt2.fee) OVER (PARTITION BY tt2.key ORDER BY tt2.time) as running_fee,