| 1 | # Use-case 0006 — View portfolio and transaction history
|
|---|
| 2 |
|
|---|
| 3 | **Initiating actor:** Trader
|
|---|
| 4 |
|
|---|
| 5 | **Other actors:** —
|
|---|
| 6 |
|
|---|
| 7 | A Trader inspects their current holdings, unrealised P/L, cash balance and recent ledger.
|
|---|
| 8 |
|
|---|
| 9 | ## Scenario
|
|---|
| 10 |
|
|---|
| 11 | ### Portfolio
|
|---|
| 12 |
|
|---|
| 13 | 1. Trader chooses "View portfolio".
|
|---|
| 14 | 2. System queries the `v_portfolio` view:
|
|---|
| 15 |
|
|---|
| 16 | ```sql
|
|---|
| 17 | SELECT symbol,
|
|---|
| 18 | quantity,
|
|---|
| 19 | COALESCE(avg_price, 0),
|
|---|
| 20 | COALESCE(current_price, 0),
|
|---|
| 21 | COALESCE(market_value, 0),
|
|---|
| 22 | COALESCE(unrealized_pnl, 0)
|
|---|
| 23 | FROM project.v_portfolio
|
|---|
| 24 | WHERE user_id = $1
|
|---|
| 25 | AND quantity > 0
|
|---|
| 26 | ORDER BY symbol;
|
|---|
| 27 | ```
|
|---|
| 28 | 3. System displays the rows and a computed summary:
|
|---|
| 29 |
|
|---|
| 30 | ```sql
|
|---|
| 31 | SELECT available_balance, invested_balance
|
|---|
| 32 | FROM project.users
|
|---|
| 33 | WHERE id = $1;
|
|---|
| 34 | ```
|
|---|
| 35 |
|
|---|
| 36 | ### Transaction history
|
|---|
| 37 |
|
|---|
| 38 | 1. Trader chooses "View transaction history".
|
|---|
| 39 | 2. System queries the last 20 ledger entries:
|
|---|
| 40 |
|
|---|
| 41 | ```sql
|
|---|
| 42 | SELECT created_at, type, amount, currency, COALESCE(description, '')
|
|---|
| 43 | FROM project.transactions
|
|---|
| 44 | WHERE user_id = $1
|
|---|
| 45 | ORDER BY created_at DESC
|
|---|
| 46 | LIMIT 20;
|
|---|
| 47 | ```
|
|---|
| 48 |
|
|---|
| 49 | ### Reference — how `v_portfolio` is defined
|
|---|
| 50 |
|
|---|
| 51 | ```sql
|
|---|
| 52 | CREATE OR REPLACE VIEW project.v_portfolio AS
|
|---|
| 53 | SELECT h.user_id,
|
|---|
| 54 | c.symbol,
|
|---|
| 55 | h.quantity,
|
|---|
| 56 | h.avg_price,
|
|---|
| 57 | lp.price AS current_price,
|
|---|
| 58 | (h.quantity * lp.price) AS market_value,
|
|---|
| 59 | (h.quantity * (lp.price - h.avg_price)) AS unrealized_pnl
|
|---|
| 60 | FROM project.holdings h
|
|---|
| 61 | JOIN project.crypto c ON c.id = h.crypto_id
|
|---|
| 62 | LEFT JOIN project.markets m
|
|---|
| 63 | ON m.crypto_id = c.id AND m.quote_currency = 'USD'
|
|---|
| 64 | LEFT JOIN project.v_latest_prices lp
|
|---|
| 65 | ON lp.market_id = m.id;
|
|---|
| 66 | ```
|
|---|