Skip to content

About

An enterprise-grade, self-hosted application for logging gold purchases, tracking spot prices, and managing your physical gold portfolio. Built for reliability, speed, and modern observability.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Gold Tracker 🚀

An enterprise-grade, self-hosted application for logging gold purchases, tracking spot prices, and managing your physical gold portfolio. Built for reliability, speed, and modern observability.

🌟 Key Features

  • Portfolio Management: Log purchases with detailed metadata (karat, weight, vendor, notes).
  • Live Price Tracking: Monitor current spot prices for 24K, 22K, 21K, and 18K gold.
  • Profit/Loss Analysis: Real-time calculation of gain/loss based on current market data.
  • AI Recommendations: Buy, sell, or hold calls generated from your own price history and holdings.
  • n8n Integration: Designed to work with n8n for automated price feeds.
  • Grafana Ready: Schema optimized for Grafana dashboards and long-term history tracking.

📈 Stocks and ETFs

The Stocks & ETFs tab tracks securities separately from physical gold and silver. Physical holdings, weight/purity calculations, metal feeds and the AI advisor are unchanged.

  1. Save a broker fee schedule: buy/sell commission percentages, a fixed per-order charge, minimum commission, and tax percentage on commission. Fixed/minimum amounts are interpreted in the trade's quote currency; create different schedules when your broker charges different currencies.
  2. Record purchases or sales with ticker, share quantity, unit execution price, currency and an explicit FX-to-BHD conversion rate (use 1 for BHD). Choose the broker to calculate the actual trade's estimated service charges.
  3. Use Update quote on a position to enter a dated market price and, for foreign currency holdings, a current FX conversion rate. Stock quotes are manual, not live, and missing quotes are shown as unknown rather than zero.

Stock cost basis uses a moving weighted-average method. Purchase fees are added to the cost basis; selling fees are deducted from net proceeds. Partial sales remove a proportional share of cost basis. Realized P/L remains available after a position closes. Trade fee amounts and exchange rates are saved at execution time and do not change when a broker schedule changes. To preserve accurate cost basis, enter each symbol's trades in chronological order.

Broker schedules are user-configured, not downloaded from a broker. Confirm exchange, clearing, stamp duties, service taxes and special fees with your broker statement; any costs not represented by the schedule are not included. Stocks and ETFs are valued before hypothetical future selling fees, and the current holdings display distinguishes missing/stale manual quotes.

Routes (session authentication required):

  • GET /api/stocks/positions — open and closed stock positions.
  • GET /api/stocks/trades, POST /api/stocks/trades — trade history and recording.
  • DELETE /api/stocks/trades/:id — undo a symbol's most recent trade (the position is rebuilt from the remaining trades; earlier trades cannot be removed because later sales were costed against them).
  • GET /api/stocks/brokers, POST /api/stocks/brokers, PUT /api/stocks/brokers/:id — fee profiles.
  • PUT /api/stocks/quotes/:symbol — manual dated market price.

Schema migration 0004_stock_trading.sql is embedded and applied automatically at backend startup; no changes to existing metal rows are needed.

🛠️ Technology Stack

  • Backend: Go (Gin Gonic) - High-performance, type-safe API.
  • Frontend: React (Vite + Tailwind CSS) - Fast, responsive, and modern UI.
  • Database: PostgreSQL - Robust relational storage.
  • Infrastructure: Docker & GitHub Actions - Containerized deployment and automated CI/CD.

🏗️ How it Works

The system consists of three main components working in harmony:

  1. The API (Go): Handles all business logic, Karat conversions, and portfolio calculations. It communicates directly with the PostgreSQL database.
  2. The UI (React): A modern dashboard that fetches data from the API and provides a clean interface for adding and tracking items.
  3. The Ecosystem:
    • Price Feeds (External): An n8n workflow typically fetches live spot prices from external APIs and pushes them into the gold_prices table.
    • AI Signals: The API generates recommendations itself and stores them in signals_log. An n8n workflow can also write there directly.
    • Dashboards: Use Grafana to visualize your portfolio growth over time by reading directly from the v_portfolio_summary view.

🚀 Getting Started

1. Database Setup

Ensure you have a PostgreSQL instance running. Use the provided setup script to initialize the schema, including all necessary tables and the portfolio summary view.

chmod +x setup_gold_db.sh
./setup_gold_db.sh

2. Configuration

Copy the .env.example to .env and configure your database credentials.

cp .env.example .env

3. Build and Deploy

The entire stack is containerized for easy deployment:

docker compose up -d --build

🔐 API Access

Every route except /api/health requires a shared bearer token. With GOLD_API_TOKEN unset the API refuses all requests rather than falling open, so a misconfigured deploy fails loudly instead of quietly serving your portfolio to the internet.

# Generate a token and put it in .env
openssl rand -base64 32
GOLD_API_TOKEN=<the generated value>

The UI container reads the same variable. nginx attaches the credential to the requests it proxies, so the token is never shipped to the browser.

Reaching the UI is therefore equivalent to holding the token. Put the UI behind whatever authentication fronts your other services before exposing it.

GOLD_ALLOWED_ORIGIN is only needed when something other than the bundled UI calls the API from a browser. Left unset, no CORS header is sent and only same-origin requests work.

🎨 Interface Conventions

The UI follows shop-floor visual management: colour is reserved for status. Green is normal, amber wants attention, red is abnormal, and everything else — figures, controls, navigation, purity marks — is neutral.

A gain, a loss, a failed request, a stale price: these carry colour, an accompanying word or glyph, and often a coloured edge on their container. Amounts, buttons and tabs deliberately do not. If every element is coloured, colour stops carrying information, so please keep new work inside that rule rather than reintroducing a decorative accent.

🧠 AI Recommendations

The API can analyse your price history and holdings and record a buy, sell, or hold call with its reasoning. It runs on your existing Claude subscription rather than metered API credits, by invoking the Claude Code CLI in headless mode.

Setup

  1. Generate a long-lived token:

    claude setup-token
  2. Set it in your .env (see .env.example for all options):

    AI_ENABLED=true
    CLAUDE_CODE_OAUTH_TOKEN=<the token from step 1>
    

The app runs normally with these unset — the Analyse button simply reports that AI is not configured.

Running outside Docker? Leave CLAUDE_CODE_OAUTH_TOKEN empty if the claude CLI is already logged in on that machine. A placeholder value overrides working session auth and every run fails with 401 Invalid bearer token. The token is only needed in a container, where no session exists.

How it runs

  • On demand: the Analyse now button. Rate limited by AI_MANUAL_COOLDOWN_SECONDS (default 60), because the API has no authentication and the subscription's rate limit is shared with your own interactive Claude Code use.
  • Automatically: when a new price arrives, at most once per AI_AUTO_MIN_HOURS (default 24).

Generation takes roughly 20 seconds, so the endpoint returns immediately and the UI polls GET /api/signals/status until it settles.

Only numeric data is sent: price history and per-karat totals. Item names, vendor, and notes never leave the database, and the returned recommendation is validated against a fixed schema before it is stored.

🗓️ Monthly report

On the 1st of each month (checked hourly, and on startup if a month was missed) the API builds a report for the previous month and saves it to monthly_reports:

  • Per item: weight, purchase price per gram, today's price per gram, total gain, and the gain during the month (from the month's opening price, or the purchase price if bought that month).
  • Each metal's open, close and range for the month, purchases made, budget used.
  • When AI is enabled, a written review with concrete next steps (web search for market news when news is on in advisor settings). Item names are replaced with neutral labels before anything is sent to the model.

Set DISCORD_WEBHOOK_URL to post the summary, a fixed-width table and the review to a Discord channel. The Reports tab lists past reports and can generate last month or the month so far on demand (POST /api/reports/generate with optional {"month": "YYYY-MM"}; regenerating a month replaces it and posts again).

The same webhook gets a price-drop alert when gold falls 5% or silver 8% below its highest price of the past week. Each slide alerts once, then again only after a further full drop or a week later.

💰 Sure sync

Set SURE_URL, SURE_API_KEY and SURE_GOLD_ACCOUNT_ID / SURE_SILVER_ACCOUNT_ID to post each metal's value to accounts in Sure, so it counts in net worth there. The first run backfills from the first purchase (weekly, daily for the last 30 days); after that the latest day is posted hourly. Sure only receives the value, never item names or prices paid.

📂 Project Structure

  • /backend: The Go API source code.
  • /frontend: The React application and its Nginx configuration.
  • /backend/migrations: Schema migrations, embedded in the binary and applied at startup.
  • .github/workflows: Automated build and deployment pipelines.

🤝 Contributing

We welcome contributions! Please feel free to submit a Pull Request.

About

An enterprise-grade, self-hosted application for logging gold purchases, tracking spot prices, and managing your physical gold portfolio. Built for reliability, speed, and modern observability.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages