Query editor
WITH positions AS (SELECT position, collateral, owner, opened_at FROM query_8336020),latest_update AS (SELECT l.contract_address AS position,bytearray_to_uint256(bytearray_substring(l.data, 1, 32)) AS collateral_raw,bytearray_to_uint256(bytearray_substring(l.data, 33, 32)) AS liq_price_raw,bytearray_to_uint256(bytearray_substring(l.data, 65, 32)) / 1e18 AS minted_zchf,ROW_NUMBER() OVER (PARTITION BY l.contract_address ORDER BY l.block_number DESC, l.index DESC) AS rnFROM ethereum.logs lJOIN positions p ON l.contract_address = p.positionWHERE l.topic0 = 0x9483a26ad376f30b5199a79e75df3bb05158c4ee32a348f53e83245a5e50c86e),bal AS ( -- live collateral actually in the position: kills phantom rows from stale eventsSELECT p.position,SUM(CASE WHEN t."to" = p.position THEN CAST(t.value AS int256)ELSE -CAST(t.value AS int256) END) AS raw_balanceFROM erc20_ethereum.evt_Transfer tJOIN positions p ON (t."to" = p.position OR t."from" = p.position)AND t.contract_address = p.collateralGROUP BY 1),chfusd AS (SELECT COALESCE((SELECT bytearray_to_uint256(bytearray_substring(l.topic1, 1, 32)) / 1e8FROM ethereum.logs lWHERE l.contract_address IN (SELECT bytearray_substring(topic2, 13, 20) FROM ethereum.logsWHERE contract_address = 0x449d117117838fFA61263B61dA6301AA2a88B13AAND topic0 = 0x33745f67a407dcb785417f9c123dd3641479a102674b6e35c1f10975625b90e9)AND l.topic0 = 0x0559884fd3a460db3073b7fc896cc77986f16e378210ded43186175bf646fc5fORDER BY l.block_number DESC LIMIT 1),CAST(1.23 AS double)) AS usd_per_chf),px AS (SELECT contract_address, price,ROW_NUMBER() OVER (PARTITION BY contract_address ORDER BY timestamp DESC) AS rnFROM prices.dayWHERE blockchain = 'ethereum')SELECT p.position, p.owner, tk.symbol AS collateral,lu.collateral_raw / POWER(10, tk.decimals) AS collateral_amount,lu.liq_price_raw / POWER(10, 36 - tk.decimals) AS liq_price_zchf,px.price / c.usd_per_chf AS mkt_price_chf,100.0 * (px.price / c.usd_per_chf- lu.liq_price_raw / POWER(10, 36 - tk.decimals))/ NULLIF(px.price / c.usd_per_chf, 0) AS buffer_pct,lu.minted_zchf,date_diff('day', p.opened_at, NOW()) AS age_daysFROM latest_update luJOIN positions p ON p.position = lu.positionJOIN bal b ON b.position = lu.position AND b.raw_balance > 0LEFT JOIN tokens.erc20 tk ON tk.contract_address = p.collateral AND tk.blockchain = 'ethereum'LEFT JOIN px ON px.contract_address = p.collateral AND px.rn = 1CROSS JOIN chfusd cWHERE lu.rn = 1 AND lu.minted_zchf > 0ORDER BY lu.minted_zchf DESC