adding position and trade endpoints

This commit is contained in:
zipfriis
2026-03-25 17:09:31 +01:00
parent 52d99c7012
commit b9f462f5be
5 changed files with 43 additions and 1 deletions

View File

@@ -30,6 +30,7 @@ func InitDB(db *sql.DB) {
CREATE TABLE IF NOT EXISTS position ( CREATE TABLE IF NOT EXISTS position (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
company_id INTEGER NOT NULL, company_id INTEGER NOT NULL,
currency_id INTEGER NOT NULL,
shares INTEGER NOT NULL, shares INTEGER NOT NULL,
weight REAL NOT NULL, weight REAL NOT NULL,
CostBases REAL NOT NULL, CostBases REAL NOT NULL,

View File

@@ -30,6 +30,29 @@ func GetTrades(db *sql.DB) ([]model.Trade, error) {
return trades, nil return trades, nil
} }
func GetPositions(db *sql.DB) ([]model.Position, error) {
rows, err := db.Query("SELECT company_id, shares, weight, CostBases, currency_id")
if err != nil {
return nil, err
}
defer rows.Close()
var positions []model.Position
for rows.Next() {
var t model.Position
err := rows.Scan(&t.Company.ID, &t.Shares, &t.Weight, &t.CostBasis, t.Currency)
if err != nil {
return nil, err
}
positions = append(positions, t)
}
if err = rows.Err(); err != nil {
return nil, err
}
return positions, nil
}
func InsertTrade(db *sql.DB, trade model.Trade) error { func InsertTrade(db *sql.DB, trade model.Trade) error {
_, err := db.Exec( _, err := db.Exec(
"INSERT INTO trades (company_id, currency_id, shares, product, type, price, traded_at) VALUES (?, ?, ?, ?, ?, ?, ?)", "INSERT INTO trades (company_id, currency_id, shares, product, type, price, traded_at) VALUES (?, ?, ?, ?, ?, ?, ?)",

View File

@@ -42,3 +42,19 @@ func GetTradeListHandler(db *sql.DB) http.HandlerFunc {
} }
} }
} }
func GetPositionListHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tradeList, err := database.GetPositions(db)
if err != nil {
http.Error(w, "failed to fetch trades", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(tradeList); err != nil {
http.Error(w, "failed to encode trades", http.StatusInternalServerError)
return
}
}
}

View File

@@ -7,7 +7,8 @@ import (
type Position struct { type Position struct {
Company Company Company Company
weight float64 Currency Currency
Weight float64
CostBasis float64 CostBasis float64
Shares int Shares int
} }

View File

@@ -38,6 +38,7 @@ func main() {
//Trades //Trades
http.HandleFunc("POST /trade/add", handlers.AddTradeHandler(db)) http.HandleFunc("POST /trade/add", handlers.AddTradeHandler(db))
http.HandleFunc("GET /trade/list", handlers.GetTradeListHandler(db)) http.HandleFunc("GET /trade/list", handlers.GetTradeListHandler(db))
http.HandleFunc("GET /positions/list", handlers.GetTradeListHandler(db))
// Company // Company
http.HandleFunc("POST /add/company", handlers.AddCompanyHandler(db)) http.HandleFunc("POST /add/company", handlers.AddCompanyHandler(db))