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