CREATE MATERIALIZED VIEW adib_rm.sdk_order_execution_aggregates_mv AS
SELECT
ex.order_id,
SUM(CAST(ex.quantity AS DECIMAL)) AS filled_quantity,
SUM(
CAST(ex.quantity AS DECIMAL) * CAST((
ex.price -> 'amount' ->> 'value'
) AS DECIMAL)
) AS total_amount,
SUM(CAST((
ex.commission -> 'amount' ->> 'value'
) AS DECIMAL)) AS total_fees,
SUM(
CAST(ex.quantity AS DECIMAL) * CAST((
ex.price -> 'amount' ->> 'value'
) AS DECIMAL)
) / NULLIF(SUM(CAST(ex.quantity AS DECIMAL)), 0) AS average_price,
MAX(ex.price -> 'currency_code' ->> 'value') AS execution_currency_code
FROM order_service.order_executions AS ex
JOIN order_service.orders AS o
ON o.id = ex.order_id
GROUP BY
ex.order_id