| 1 | package main
|
|---|
| 2 |
|
|---|
| 3 | import (
|
|---|
| 4 | "fmt"
|
|---|
| 5 |
|
|---|
| 6 | "bp_project/server/db"
|
|---|
| 7 | )
|
|---|
| 8 |
|
|---|
| 9 | // ShowPortfolio - UC0006
|
|---|
| 10 | // Uses the v_portfolio view to list holdings with current market value and P&L.
|
|---|
| 11 | func ShowPortfolio(s *Session) {
|
|---|
| 12 | rows, err := db.DB.Query(
|
|---|
| 13 | `SELECT symbol,
|
|---|
| 14 | quantity,
|
|---|
| 15 | COALESCE(avg_price, 0),
|
|---|
| 16 | COALESCE(current_price, 0),
|
|---|
| 17 | COALESCE(market_value, 0),
|
|---|
| 18 | COALESCE(unrealized_pnl, 0)
|
|---|
| 19 | FROM v_portfolio
|
|---|
| 20 | WHERE user_id = $1 AND quantity > 0
|
|---|
| 21 | ORDER BY symbol`,
|
|---|
| 22 | s.UserID,
|
|---|
| 23 | )
|
|---|
| 24 | if err != nil {
|
|---|
| 25 | fmt.Println("Error:", err)
|
|---|
| 26 | return
|
|---|
| 27 | }
|
|---|
| 28 | defer rows.Close()
|
|---|
| 29 |
|
|---|
| 30 | fmt.Println()
|
|---|
| 31 | fmt.Printf(" %-8s %12s %14s %14s %14s %14s\n",
|
|---|
| 32 | "Symbol", "Quantity", "Avg buy", "Current", "Value", "Unrealised P/L")
|
|---|
| 33 | fmt.Println(" ------------------------------------------------------------------------------------")
|
|---|
| 34 |
|
|---|
| 35 | var totalValue, totalPnL float64
|
|---|
| 36 | empty := true
|
|---|
| 37 | for rows.Next() {
|
|---|
| 38 | var sym string
|
|---|
| 39 | var qty, avg, cur, val, pnl float64
|
|---|
| 40 | if err := rows.Scan(&sym, &qty, &avg, &cur, &val, &pnl); err != nil {
|
|---|
| 41 | fmt.Println("scan error:", err)
|
|---|
| 42 | return
|
|---|
| 43 | }
|
|---|
| 44 | fmt.Printf(" %-8s %12.4f %14.6f %14.6f %14.4f %+14.4f\n",
|
|---|
| 45 | sym, qty, avg, cur, val, pnl)
|
|---|
| 46 | totalValue += val
|
|---|
| 47 | totalPnL += pnl
|
|---|
| 48 | empty = false
|
|---|
| 49 | }
|
|---|
| 50 | if empty {
|
|---|
| 51 | fmt.Println(" (no holdings yet)")
|
|---|
| 52 | return
|
|---|
| 53 | }
|
|---|
| 54 | fmt.Println(" ------------------------------------------------------------------------------------")
|
|---|
| 55 | fmt.Printf(" %-8s %12s %14s %14s %14.4f %+14.4f\n",
|
|---|
| 56 | "TOTAL", "", "", "", totalValue, totalPnL)
|
|---|
| 57 |
|
|---|
| 58 | // cash summary
|
|---|
| 59 | var avail, invested float64
|
|---|
| 60 | _ = db.DB.QueryRow(
|
|---|
| 61 | `SELECT available_balance, invested_balance FROM users WHERE id = $1`,
|
|---|
| 62 | s.UserID,
|
|---|
| 63 | ).Scan(&avail, &invested)
|
|---|
| 64 | fmt.Printf("\n Cash available : %.4f USD\n", avail)
|
|---|
| 65 | fmt.Printf(" Portfolio value: %.4f USD\n", totalValue)
|
|---|
| 66 | fmt.Printf(" Net worth : %.4f USD\n", avail+totalValue)
|
|---|
| 67 | }
|
|---|