| 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(reserved_quantity, 0),
|
|---|
| 20 | COALESCE(available_quantity, quantity),
|
|---|
| 21 | COALESCE(avg_price, 0),
|
|---|
| 22 | COALESCE(current_price, 0),
|
|---|
| 23 | COALESCE(market_value, 0),
|
|---|
| 24 | COALESCE(unrealized_pnl, 0)
|
|---|
| 25 | FROM project.v_portfolio
|
|---|
| 26 | WHERE user_id = $1
|
|---|
| 27 | AND quantity > 0
|
|---|
| 28 | ORDER BY symbol;
|
|---|
| 29 | ```
|
|---|
| 30 |
|
|---|
| 31 | `reserved_quantity` is the amount committed to the Trader's own open sell
|
|---|
| 32 | orders (see [UseCase0005](UseCase0005.md)); `available_quantity` is what is
|
|---|
| 33 | actually free to sell right now.
|
|---|
| 34 | 3. System displays the rows and a computed summary:
|
|---|
| 35 |
|
|---|
| 36 | ```sql
|
|---|
| 37 | SELECT available_balance, invested_balance
|
|---|
| 38 | FROM project.users
|
|---|
| 39 | WHERE id = $1;
|
|---|
| 40 | ```
|
|---|
| 41 |
|
|---|
| 42 | ### Transaction history
|
|---|
| 43 |
|
|---|
| 44 | 1. Trader chooses "View transaction history".
|
|---|
| 45 | 2. System queries the last 20 ledger entries:
|
|---|
| 46 |
|
|---|
| 47 | ```sql
|
|---|
| 48 | SELECT created_at, type, amount, currency, COALESCE(description, '')
|
|---|
| 49 | FROM project.transactions
|
|---|
| 50 | WHERE user_id = $1
|
|---|
| 51 | ORDER BY created_at DESC
|
|---|
| 52 | LIMIT 20;
|
|---|
| 53 | ```
|
|---|
| 54 |
|
|---|
| 55 | ### Reference — how `v_portfolio` is defined
|
|---|
| 56 |
|
|---|
| 57 | ```sql
|
|---|
| 58 | CREATE OR REPLACE VIEW project.v_portfolio AS
|
|---|
| 59 | SELECT h.user_id,
|
|---|
| 60 | c.symbol,
|
|---|
| 61 | h.quantity,
|
|---|
| 62 | h.reserved_quantity,
|
|---|
| 63 | (h.quantity - h.reserved_quantity) AS available_quantity,
|
|---|
| 64 | h.avg_price,
|
|---|
| 65 | lp.price AS current_price,
|
|---|
| 66 | (h.quantity * lp.price) AS market_value,
|
|---|
| 67 | (h.quantity * (lp.price - h.avg_price)) AS unrealized_pnl
|
|---|
| 68 | FROM project.holdings h
|
|---|
| 69 | JOIN project.crypto c ON c.id = h.crypto_id
|
|---|
| 70 | LEFT JOIN project.markets m
|
|---|
| 71 | ON m.crypto_id = c.id AND m.quote_currency = 'USD'
|
|---|
| 72 | LEFT JOIN project.v_latest_prices lp
|
|---|
| 73 | ON lp.market_id = m.id;
|
|---|
| 74 | ```
|
|---|