Query editor
WITH tokenInfo(contract_address, token) AS (VALUES(0x82af49447d8a07e3bd95bd0d56f35241523fbab1, 'WETH'),(0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f, 'WBTC'),(0xf97f4df75117a78c1a5a0dbb814af92458539fb4, 'LINK'),(0xfa7f8980b0f1e64a2062791cc3b0871572f1f7f0, 'UNI')),trades_tmp as (SELECT trades.time, account, ROUND(price,8) as price, key, i.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,-- 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 collatDeltaFROM gmx_arbitrum.Vault_evt_IncreasePositionUNION 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 collatDeltaFROM gmx_arbitrum.Vault_evt_LiquidatePositionUNION 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 collatDeltaFROM gmx_arbitrum.Vault_evt_DecreasePosition) as trades join tokenInfo i on indexToken = i.contract_addressWHERE i.token = '{{Token_open}}' and position_side = 'SHORT'-- 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,(CASE WHEN tt3.grp is NULL THEN 'OPEN' ELSE 'CLOSED' END) as stateFROM trades_tmp2 tt2 LEFT OUTER JOIN-- All groups that have a running_total_size of 0 are closed trades(SELECT account, token, position_side, grp FROM trades_tmp2 WHERE running_total_size=0) tt3on tt2.account = tt3.accountand tt2.grp = tt3.grpand tt2.token = tt3.tokenand tt2.position_side = tt3.position_sideWHERE tt3.grp is NULLORDER BY tt2.account, tt2.token, time asc),data as (SELECT min(time) as open_time, key, account, token from trades_tmp3group by 2,3,4),