From a61079769b0f1f1c5f675147bf26bfff82a34916 Mon Sep 17 00:00:00 2001 From: Peter Wood Date: Fri, 14 Nov 2025 13:16:44 -0500 Subject: [PATCH] Refactor documentation: Remove outdated guides on CI/CD setup, multi-user support, and SSO authentication; update index and quickstart pages for clarity and improved structure; enhance feature descriptions and application overview. --- README.md | 44 ++- docs.json | 17 +- features/portfolio-management.mdx | 57 ++-- guides/deployment/caddy.mdx | 393 --------------------------- guides/deployment/docker.mdx | 426 ------------------------------ guides/setup/cicd.mdx | 283 -------------------- guides/setup/multi-user.mdx | 262 ------------------ guides/setup/sso.mdx | 234 ---------------- index.mdx | 91 +++---- quickstart.mdx | 332 +++++++++++------------ 10 files changed, 265 insertions(+), 1874 deletions(-) delete mode 100644 guides/deployment/caddy.mdx delete mode 100644 guides/deployment/docker.mdx delete mode 100644 guides/setup/cicd.mdx delete mode 100644 guides/setup/multi-user.mdx delete mode 100644 guides/setup/sso.mdx diff --git a/README.md b/README.md index 055c983..801360c 100644 --- a/README.md +++ b/README.md @@ -1,43 +1,41 @@ -# Mintlify Starter Kit +# Trading Analysis Dashboard Documentation -Use the starter kit to get your docs deployed and ready to customize. +This repository contains the documentation for the Trading Analysis Dashboard application - a Flask-based web platform for tracking and analyzing stock trading performance with real-time portfolio management. -Click the green **Use this template** button at the top of this repo to copy the Mintlify starter kit. The starter kit contains examples with +## Documentation Structure -- Guide pages -- Navigation -- Customizations -- API reference pages -- Use of popular components +- **Overview** - Application architecture, data models, and core concepts +- **Features** - Detailed documentation of portfolio tracking, trading analysis, and data import capabilities +- **API Reference** - RESTful API endpoint documentation with examples -**[Follow the full quickstart guide](https://starter.mintlify.com/quickstart)** +## Local Development -## Development +Install the [Mintlify CLI](https://www.npmjs.com/package/mint) to preview documentation changes locally: -Install the [Mintlify CLI](https://www.npmjs.com/package/mint) to preview your documentation changes locally. To install, use the following command: - -``` +```bash npm i -g mint ``` -Run the following command at the root of your documentation, where your `docs.json` is located: +Run the following command at the root of the documentation directory: -``` +```bash mint dev ``` View your local preview at `http://localhost:3000`. -## Publishing changes +## Publishing Changes -Install our GitHub app from your [dashboard](https://dashboard.mintlify.com/settings/organization/github-app) to propagate changes from your repo to your deployment. Changes are deployed to production automatically after pushing to the default branch. +Changes are automatically deployed to production after pushing to the default branch via GitHub integration. -## Need help? +## About the Application -### Troubleshooting +The Trading Analysis Dashboard provides: -- If your dev environment isn't running: Run `mint update` to ensure you have the most recent version of the CLI. -- If a page loads as a 404: Make sure you are running in a folder with a valid `docs.json`. +- **Portfolio Management** - Track stocks, ETFs, and mutual funds with real-time pricing +- **Trading Analysis** - Monthly P&L reports with trade-by-trade detail +- **Hybrid Matching** - Broker-level accuracy combining realized gains and transaction history +- **CSV Import** - Bulk data import for holdings and transactions +- **Multi-User Support** - OAuth authentication with isolated user data -### Resources -- [Mintlify documentation](https://mintlify.com/docs) +Built with Flask, PostgreSQL, and integrating with Finnhub for real-time market data. diff --git a/docs.json b/docs.json index e5445f4..c7c8323 100644 --- a/docs.json +++ b/docs.json @@ -14,27 +14,12 @@ "tab": "Documentation", "groups": [ { - "group": "Getting Started", + "group": "Overview", "pages": [ "index", "quickstart" ] }, - { - "group": "Setup & Configuration", - "pages": [ - "guides/setup/cicd", - "guides/setup/sso", - "guides/setup/multi-user" - ] - }, - { - "group": "Deployment", - "pages": [ - "guides/deployment/docker", - "guides/deployment/caddy" - ] - }, { "group": "Features", "pages": [ diff --git a/features/portfolio-management.mdx b/features/portfolio-management.mdx index fdf3017..f8b4823 100644 --- a/features/portfolio-management.mdx +++ b/features/portfolio-management.mdx @@ -24,32 +24,9 @@ The Portfolio Management feature allows you to track your current stock, ETF, an -## Quick Start +## Using the Portfolio - - - Register at [Finnhub.io](https://finnhub.io/register) and copy your API key - - - - Add your API key to `.env`: - ```bash - FINNHUB_API_KEY=your_api_key_here - ``` - - - - Use the web interface to add holdings manually or upload a CSV file - - - - Click "Refresh Prices" to fetch current market prices - - - -## Adding Holdings - -### Manual Entry +### Adding Holdings @@ -141,6 +118,36 @@ The free Finnhub API tier allows: The application intelligently manages API requests to stay within these limits. +## Technical Details + +### Price Update Logic + +When refreshing prices, the application: + +1. Checks the last update timestamp +2. If > 15 minutes old, fetches new prices +3. Makes API calls in batches to respect rate limits +4. Updates the database with new prices and timestamp +5. Recalculates portfolio metrics + +### Data Storage + +Holdings are stored in the `holdings` table with the following schema: + +```sql +CREATE TABLE holdings ( + id SERIAL PRIMARY KEY, + user_id INTEGER REFERENCES users(id), + symbol VARCHAR(10) NOT NULL, + type VARCHAR(20) NOT NULL, + shares DECIMAL(10,4) NOT NULL, + average_cost DECIMAL(10,2) NOT NULL, + current_price DECIMAL(10,2), + last_updated TIMESTAMP, + notes TEXT +); +``` + ## Next Steps diff --git a/guides/deployment/caddy.mdx b/guides/deployment/caddy.mdx deleted file mode 100644 index 39fd92b..0000000 --- a/guides/deployment/caddy.mdx +++ /dev/null @@ -1,393 +0,0 @@ ---- -title: 'Caddy Configuration' -description: 'Configure Caddy reverse proxy for different deployment scenarios' ---- - -## Overview - -Caddy is a powerful web server that automatically handles HTTPS with Let's Encrypt. This guide explains how to configure Caddy for different deployment scenarios. - -## Local Development - -The default `Caddyfile` is configured for local development: - -```caddy Caddyfile -localhost { - reverse_proxy trading_app:5000 - encode gzip - header { - X-Content-Type-Options nosniff - X-Frame-Options DENY - X-XSS-Protection "1; mode=block" - Referrer-Policy "strict-origin-when-cross-origin" - -Server - } -} -``` - - - Access your app at: `http://localhost` - - -## Production Deployment - -### Step 1: Domain Setup - - - - Point your domain's DNS A record to your server's IP - - - - ```bash - cp Caddyfile.production Caddyfile - ``` - - - - Replace `your-domain.com` with your actual domain - - - -### Step 2: Environment Configuration - -Update your `.env` file: - -```env .env -DOMAIN=your-domain.com -FLASK_ENV=production -``` - -### Step 3: Deploy - -```bash -docker-compose up -d -``` - - - Caddy will automatically: - - Obtain SSL certificates from Let's Encrypt - - Handle HTTP to HTTPS redirects - - Renew certificates automatically - - -## Configuration Options - -### Basic Reverse Proxy - -```caddy -your-domain.com { - reverse_proxy trading_app:5000 -} -``` - -### With Compression and Security Headers - -```caddy -your-domain.com { - reverse_proxy trading_app:5000 - encode gzip - - header { - X-Content-Type-Options nosniff - X-Frame-Options DENY - Strict-Transport-Security "max-age=31536000" - } -} -``` - -### Static File Caching - -```caddy -your-domain.com { - reverse_proxy trading_app:5000 - - @static path /static/* - handle @static { - header Cache-Control "public, max-age=3600" - reverse_proxy trading_app:5000 - } -} -``` - -### Rate Limiting - -```caddy -your-domain.com { - rate_limit { - zone general 10r/s - } - reverse_proxy trading_app:5000 -} -``` - -### Basic Authentication - -```caddy -admin.your-domain.com { - basicauth { - admin $2a$14$hashed_password_here - } - reverse_proxy trading_app:5000 -} -``` - -## SSL/TLS Configuration - -### Automatic HTTPS (Default) - -Caddy automatically obtains certificates from Let's Encrypt: - -```caddy -your-domain.com { - reverse_proxy trading_app:5000 -} -``` - - - No additional configuration needed! Caddy handles everything automatically. - - -### Custom Certificates - -```caddy -your-domain.com { - tls /path/to/cert.pem /path/to/key.pem - reverse_proxy trading_app:5000 -} -``` - -### Internal/Self-Signed Certificates - -```caddy -your-domain.com { - tls internal - reverse_proxy trading_app:5000 -} -``` - -## Monitoring and Logging - -### Access Logs - -```caddy -your-domain.com { - reverse_proxy trading_app:5000 - - log { - output file /var/log/caddy/access.log - format json - } -} -``` - -### Error Handling - -```caddy -your-domain.com { - reverse_proxy trading_app:5000 - - handle_errors { - @404 expression {http.error.status_code} == 404 - handle @404 { - rewrite * /404.html - reverse_proxy trading_app:5000 - } - } -} -``` - -## Advanced Features - -### Multiple Domains - -```caddy -site1.com, site2.com { - reverse_proxy trading_app:5000 -} -``` - -### Subdomain Routing - -```caddy -api.your-domain.com { - reverse_proxy trading_app:5000/api -} - -app.your-domain.com { - reverse_proxy trading_app:5000 -} -``` - -### Load Balancing - -```caddy -your-domain.com { - reverse_proxy trading_app1:5000 trading_app2:5000 { - lb_policy round_robin - health_path /health - } -} -``` - -## Troubleshooting - -### Check Caddy Status - -```bash -docker-compose logs caddy -``` - -### Certificate Issues - -```bash -# Check certificate status -docker-compose exec caddy caddy list-certificates - -# Force certificate renewal -docker-compose exec caddy caddy reload --config /etc/caddy/Caddyfile -``` - -### Configuration Validation - -```bash -# Validate Caddyfile syntax -docker-compose exec caddy caddy validate --config /etc/caddy/Caddyfile -``` - -### Common Issues - - - - ```bash - # Check what's using the ports - netstat -tlnp | grep :80 - netstat -tlnp | grep :443 - ``` - - Stop the conflicting service or change Caddy's ports in docker-compose.yml - - - - ```bash - # Check DNS resolution - nslookup your-domain.com - ``` - - Verify your domain's A record points to the correct IP address - - - - Use staging environment for testing: - - ```caddy - your-domain.com { - tls { - ca https://acme-staging-v02.api.letsencrypt.org/directory - } - reverse_proxy trading_app:5000 - } - ``` - - - - - Ensure port 80 is accessible from the internet - - Verify DNS is propagated: `dig your-domain.com` - - Check firewall rules allow incoming connections - - Review Caddy logs for specific errors - - - -## Performance Tuning - -### Enable HTTP/2 and HTTP/3 - -```caddy -your-domain.com { - protocols h1 h2 h3 - reverse_proxy trading_app:5000 -} -``` - -### Connection Limits - -```caddy -your-domain.com { - reverse_proxy trading_app:5000 { - transport http { - max_conns_per_host 100 - } - } -} -``` - -### Timeout Configuration - -```caddy -your-domain.com { - reverse_proxy trading_app:5000 { - transport http { - read_timeout 30s - write_timeout 30s - } - } -} -``` - -## Security Best Practices - - - - Use TLS 1.2+ with strong cipher suites (Caddy's default) - - - Add security headers like CSP, HSTS, X-Frame-Options - - - Implement rate limiting to prevent abuse - - - Use basic auth or OAuth for sensitive routes - - - -### Recommended Security Configuration - -```caddy -your-domain.com { - reverse_proxy trading_app:5000 - - encode gzip - - header { - # Security headers - Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" - X-Content-Type-Options "nosniff" - X-Frame-Options "DENY" - X-XSS-Protection "1; mode=block" - Referrer-Policy "strict-origin-when-cross-origin" - Permissions-Policy "geolocation=(), microphone=(), camera=()" - - # Hide server info - -Server - -X-Powered-By - } -} -``` - -## Additional Resources - - - - Official Caddy documentation - - - Learn Caddyfile syntax - - - How Caddy handles HTTPS automatically - - - Back to Docker deployment guide - - diff --git a/guides/deployment/docker.mdx b/guides/deployment/docker.mdx deleted file mode 100644 index a2eb27c..0000000 --- a/guides/deployment/docker.mdx +++ /dev/null @@ -1,426 +0,0 @@ ---- -title: 'Docker Deployment' -description: 'Deploy the Trading Analysis Dashboard using Docker containers' ---- - -## Quick Start - - - - Install [Docker Desktop](https://www.docker.com/products/docker-desktop/) (includes Docker Compose) - - - - - - ```batch - deploy.bat - ``` - - - ```bash - chmod +x deploy.sh - ./deploy.sh - ``` - - - - - - ```bash - # Copy environment file - cp .env.docker .env - - # Build and start services - docker compose up -d - - # Check status - docker compose ps - ``` - - - -## Services Overview - -The deployment includes these services: - -| Service | Port | Description | -|---------|------|-------------| -| **trading_app** | 8080 | Main Flask application | -| **postgres** | 5432 | PostgreSQL database | -| **caddy** | 80, 443 | Reverse proxy with automatic HTTPS | - -## Access URLs - - - - https://performance.miningwood.com - - - http://localhost:8080 - - - http://localhost - - - localhost:5432 - - - -## Docker Compose Configuration - -The complete `docker-compose.yml` file for the application: - -```yaml docker-compose.yml -services: - server: - image: docker.gitea.com/gitea:latest - container_name: gitea - environment: - - USER_UID=${USER_UID} - - USER_GID=${USER_GID} - - GITEA__database__DB_TYPE=postgres - - GITEA__database__HOST=db:5432 - - GITEA__database__NAME=${POSTGRES_USER} - - GITEA__database__USER=${POSTGRES_USER} - - GITEA__database__PASSWD=${POSTGRES_PASSWORD} - restart: always - networks: - - gitea - volumes: - - gitea:/data - - /etc/timezone:/etc/timezone:ro - - /etc/localtime:/etc/localtime:ro - ports: - - ${GITEA_HTTP_PORT:-3500}:3000 - - ${GITEA_SSH_PORT:-2229}:22 - depends_on: - - db - labels: - - diun.enable=true - healthcheck: - test: - - CMD - - curl - - -f - - http://localhost - interval: 10s - retries: 3 - start_period: 30s - timeout: 10s - - db: - image: docker.io/library/postgres:14 - restart: always - environment: - - POSTGRES_USER=${POSTGRES_USER} - - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - - POSTGRES_DB=${POSTGRES_DB} - networks: - - gitea - volumes: - - postgres:/var/lib/postgresql/data - - runner: - image: gitea/act_runner:latest - container_name: gitea-runner - restart: always - networks: - - gitea - volumes: - - runner:/data - - /var/run/docker.sock:/var/run/docker.sock - - ./runner-config.yaml:/data/config.yaml:ro - environment: - - GITEA_INSTANCE_URL=http://server:3000 - - GITEA_RUNNER_REGISTRATION_TOKEN=${GITEA_RUNNER_REGISTRATION_TOKEN} - - GITEA_RUNNER_NAME=docker-runner - - CONFIG_FILE=/data/config.yaml - command: > - sh -c " - if [ ! -f /data/.runner ]; then - act_runner register --no-interactive --instance http://server:3000 --token $${GITEA_RUNNER_REGISTRATION_TOKEN} --name docker-runner; - fi; - act_runner --config /data/config.yaml daemon - " - depends_on: - - server - labels: - - diun.enable=true - -networks: - gitea: - external: false - -volumes: - gitea: - postgres: - runner: -``` - -## Configuration - -### Environment Variables - -Edit the `.env` file to customize your deployment: - -```env .env -# Database Configuration -DB_HOST=postgres -DB_PORT=5432 -DB_NAME=mining_wood -DB_USER=trading_user -DB_PASSWORD=your_secure_password - -# Flask Configuration -FLASK_SECRET_KEY=your-super-secret-key-change-this -FLASK_ENV=production - -# Gitea Configuration -USER_UID=1000 -USER_GID=1000 -POSTGRES_USER=gitea -POSTGRES_PASSWORD=gitea_password -POSTGRES_DB=gitea -GITEA_HTTP_PORT=3500 -GITEA_SSH_PORT=2229 -GITEA_RUNNER_REGISTRATION_TOKEN=your_token_here -``` - - - Always change default passwords before deploying to production! - - -### SSL/HTTPS Setup with Caddy - -Caddy provides automatic HTTPS with Let's Encrypt: - - - - No setup needed - uses HTTP by default - - - - ```bash - # Edit Caddyfile and replace localhost with your domain - cp Caddyfile.production Caddyfile - # Edit the domain in Caddyfile: your-domain.com - ``` - - Caddy will automatically get and renew SSL certificates! - - - -## Database Setup - -The PostgreSQL database is automatically initialized with: -- **Database**: `mining_wood` -- **Schema**: `trading_analysis` -- **User**: `trading_user` - -### Import Your Trading Data - -After deployment, import your trading data: - - - - ```bash - docker compose exec postgres psql -U trading_user -d mining_wood - ``` - - - - ```bash - # Copy your CSV files to the container - docker cp your-data.csv trading_app:/app/data/ - - # Run your import script - docker compose exec trading_app python your_import_script.py - ``` - - - -## Management Commands - -### View Logs - -```bash -# All services -docker compose logs -f - -# Specific service -docker compose logs -f trading_app -docker compose logs -f postgres -docker compose logs -f caddy -``` - -### Restart Services - -```bash -# Restart all services -docker compose restart - -# Restart specific service -docker compose restart trading_app -``` - -### Stop/Start - -```bash -# Stop all services -docker compose down - -# Start services -docker compose up -d - -# Stop and remove volumes (⚠️ removes database data) -docker compose down -v -``` - -### Update Application - -```bash -# Pull latest images and restart -docker compose pull -docker compose up -d -``` - -### Database Backup - -```bash -# Backup database -docker compose exec postgres pg_dump -U trading_user mining_wood > backup.sql - -# Restore database -docker compose exec -T postgres psql -U trading_user mining_wood < backup.sql -``` - -## Security Considerations - -### For Production Deployment - - - - Update `POSTGRES_PASSWORD` and `FLASK_SECRET_KEY` in docker compose.yml/.env - - - Configure SSL certificates and enable HTTPS redirect - - - Only expose necessary ports (80, 443). Restrict database access (5432) - - - Keep Docker images updated and monitor security advisories - - - -## Production Deployment - -### Domain Setup - - - - - Point your domain to your server's IP address - - For performance.miningwood.com: Create an A record pointing to your server IP - - - - ```bash - # Caddy handles SSL automatically with Let's Encrypt - # The domain is already configured for performance.miningwood.com - # Just deploy and Caddy will handle the rest - docker compose up -d - ``` - - - - - Domain is already set to `performance.miningwood.com` in `.env.docker` - - Set `FLASK_ENV=production` - - Use strong passwords - - - -### Monitoring - -Consider adding monitoring services: - -```yaml docker-compose.yml -# Add to docker compose.yml -prometheus: - image: prom/prometheus - ports: - - "9090:9090" - -grafana: - image: grafana/grafana - ports: - - "3000:3000" -``` - -## Troubleshooting - - - - ```bash - # Check logs - docker compose logs trading_app - - # Common issues: - # - Database connection failure - # - Missing environment variables - # - Port conflicts - ``` - - - - ```bash - # Check database status - docker compose exec postgres pg_isready -U trading_user - - # Reset database - docker compose down -v - docker compose up -d - ``` - - - - ```bash - # Check resource usage - docker stats - - # Scale services - docker compose up -d --scale trading_app=2 - ``` - - - - - Ensure DNS is pointing to correct server - - Wait a few minutes for certificate provisioning - - Check Caddy logs: `docker compose logs caddy` - - - -## Development Mode - -To run in development mode: - -```bash -# Use development override -docker compose -f docker compose.yml -f docker compose.dev.yml up -d -``` - -This enables: -- Live code reloading -- Debug mode -- Development tools - -## Next Steps - - - - Learn more about Caddy reverse proxy setup - - - Automate deployments with CI/CD - - diff --git a/guides/setup/cicd.mdx b/guides/setup/cicd.mdx deleted file mode 100644 index 6f6e782..0000000 --- a/guides/setup/cicd.mdx +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: 'CI/CD Setup with Gitea' -description: 'Set up continuous integration and deployment using Gitea Actions' ---- - -## Overview - -This guide will help you set up continuous integration and continuous deployment (CI/CD) for your trading analysis application using Gitea Actions. - -## Prerequisites - -Before starting, ensure you have: - - - - Running and accessible Gitea instance - - - Docker, Docker Compose, SSH access, and Git installed - - - Domain pointing to your production server - - - SSH key pair for deployment access - - - -## Step 1: Repository Setup - -Push your code to Gitea and enable Actions: - -```bash -git remote add origin https://your-gitea-instance.com/your-username/stocks-trading-analysis.git -git push -u origin main -``` - - - - Go to Repository Settings → Actions and enable Actions for this repository - - - -## Step 2: Configure Repository Secrets - -Navigate to your repository → Settings → Secrets and add the following secrets: - -### Required Secrets - -| Secret Name | Description | Example | -|-------------|-------------|---------| -| `SSH_PRIVATE_KEY` | SSH private key for production server access | `-----BEGIN OPENSSH PRIVATE KEY-----\n...` | -| `PRODUCTION_HOST` | Production server IP or hostname | `203.0.113.1` or `server.example.com` | -| `PRODUCTION_USER` | SSH username for production server | `ubuntu`, `root`, or your username | -| `DOMAIN` | Your production domain | `performance.miningwood.com` | - -### Application Secrets - -| Secret Name | Description | Example | -|-------------|-------------|---------| -| `FLASK_SECRET_KEY` | Flask session secret key | `your-very-secure-secret-key-here` | -| `POSTGRES_PASSWORD` | Production database password | `secure-database-password` | -| `GOOGLE_CLIENT_ID` | OAuth Google Client ID | `123456789.apps.googleusercontent.com` | -| `GOOGLE_CLIENT_SECRET` | OAuth Google Client Secret | `GOCSPX-your-client-secret` | -| `AUTHORIZED_USERS` | Comma-separated authorized emails | `admin@example.com,user@example.com` | - -### Optional Notification Secrets - -| Secret Name | Description | -|-------------|-------------| -| `SLACK_WEBHOOK_URL` | Slack webhook for notifications | -| `DISCORD_WEBHOOK_URL` | Discord webhook for notifications | - -## Step 3: Production Server Setup - -### Create Application Directory - -```bash -# SSH into your production server -ssh your-user@your-production-server - -# Create application directory -sudo mkdir -p /opt/stocks-trading-analysis -sudo chown $USER:$USER /opt/stocks-trading-analysis -cd /opt/stocks-trading-analysis - -# Clone the repository -git clone https://your-gitea-instance.com/your-username/stocks-trading-analysis.git . -``` - -### Configure Environment Variables - -```bash -# Copy the production environment template -cp .gitea/deployment/production.env .env - -# Edit the environment file with your actual values -nano .env -``` - -Update the following values in `.env`: -- `POSTGRES_PASSWORD`: Set a secure database password -- `FLASK_SECRET_KEY`: Generate a secure secret key -- `GOOGLE_CLIENT_ID` & `GOOGLE_CLIENT_SECRET`: Your OAuth credentials -- `AUTHORIZED_USERS`: List of authorized email addresses -- `DOMAIN`: Your production domain name - -### Initial Deployment - -```bash -# Make deployment script executable -chmod +x .gitea/deployment/deploy.sh - -# Run initial deployment -./deploy.sh -``` - -## Step 4: SSH Key Setup - -### Generate SSH Key Pair (if needed) - -```bash -# On your local machine or CI/CD runner -ssh-keygen -t ed25519 -C "gitea-actions-deployment" -f ~/.ssh/gitea_deploy_key -``` - -### Add Public Key to Production Server - -```bash -# Copy public key to production server -ssh-copy-id -i ~/.ssh/gitea_deploy_key.pub your-user@your-production-server - -# Or manually add to authorized_keys -cat ~/.ssh/gitea_deploy_key.pub | ssh your-user@your-production-server "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys" -``` - -### Add Private Key to Gitea Secrets - -```bash -# Copy private key content -cat ~/.ssh/gitea_deploy_key - -# Add this content to the SSH_PRIVATE_KEY secret in Gitea -``` - -## Step 5: Test the CI/CD Pipeline - -### Trigger First Pipeline - - - - Make a small change to your code - - - ```bash - git add . - git commit -m "Test CI/CD pipeline" - git push origin main - ``` - - - Check the Actions tab in your Gitea repository to see the pipeline running - - - -### Verify Deployment - - - - Visit `https://your-domain.com` to verify the application is running - - - SSH to server and run `docker compose logs -f` - - - Run `docker compose ps` to check service status - - - -## Workflow Overview - -### Automatic Triggers - -- **Push to main/master**: Triggers full CI/CD pipeline with production deployment -- **Push to develop**: Triggers CI/CD pipeline with staging deployment (if configured) -- **Pull requests**: Triggers testing and build validation only -- **Schedule**: Security scans run weekly, cleanup runs weekly - -### Manual Triggers - -Navigate to Actions tab in your repository, click "Run workflow" on any workflow, select branch and run. - -## Monitoring and Maintenance - -### Check Application Health - -```bash -# SSH to production server -ssh your-user@your-production-server - -# Check service status -docker compose ps - -# View logs -docker compose logs -f trading_app - -# Check resource usage -docker stats -``` - -### Database Backups - -Backups are automatically created during deployments and stored in `/opt/backups/stocks-app/`. - -```bash -# Manual backup -docker compose exec postgres pg_dump -U trading_user mining_wood | gzip > backup_$(date +%Y%m%d_%H%M%S).sql.gz - -# Restore from backup -gunzip -c backup_file.sql.gz | docker compose exec -T postgres psql -U trading_user mining_wood -``` - -### SSL Certificate - -Caddy automatically handles SSL certificates. Check certificate status: - -```bash -# Check certificate -echo | openssl s_client -servername your-domain.com -connect your-domain.com:443 2>/dev/null | openssl x509 -noout -dates -``` - -## Troubleshooting - - - - - Verify SSH key is correctly formatted in secrets - - Check server SSH configuration - - Ensure server is accessible from internet - - - - - Check Dockerfile syntax - - Verify all dependencies in requirements.txt - - Check for file permission issues - - - - - Check environment variables in .env - - Verify database is running: `docker compose logs postgres` - - Check application logs: `docker compose logs trading_app` - - - - - Ensure DNS is pointing to correct server - - Wait a few minutes for certificate provisioning - - Check Caddy logs: `docker compose logs caddy` - - - -## Security Best Practices - - - Remember to regularly rotate secrets and monitor deployment logs for suspicious activity. - - -1. **Regularly rotate secrets** (SSH keys, database passwords) -2. **Monitor deployment logs** for suspicious activity -3. **Keep dependencies updated** (run security scans) -4. **Use strong passwords** for all services -5. **Backup regularly** and test restore procedures -6. **Monitor server resources** and set up alerts - -## Customization - -You can customize the CI/CD pipeline by modifying files in `.gitea/workflows/`: - -- `main.yml`: Main CI/CD pipeline -- `security.yml`: Security scanning -- `cleanup.yml`: Resource cleanup and maintenance - - - Remember to test changes in a staging environment before deploying to production! - diff --git a/guides/setup/multi-user.mdx b/guides/setup/multi-user.mdx deleted file mode 100644 index 9bbb567..0000000 --- a/guides/setup/multi-user.mdx +++ /dev/null @@ -1,262 +0,0 @@ ---- -title: 'Multi-User Support' -description: 'Configure multi-user support with separate brokerage accounts' ---- - -## Overview - -The application supports multiple users, each with their own brokerage account numbers and transaction data. Users authenticate via Google OAuth and can set up their brokerage account number in their profile. - -## Database Schema Changes - -### New Tables - -#### `trading_analysis.users` -Stores user information from OAuth: - -| Column | Type | Description | -|--------|------|-------------| -| `id` | Primary Key | User identifier | -| `email` | Unique | User email address | -| `name` | String | User's full name | -| `google_sub` | String | Google OAuth subject ID | -| `picture_url` | String | Profile picture URL | -| `brokerage_account_number` | String | User's primary account | -| `is_active` | Boolean | Account active status | -| `created_at` | Timestamp | Creation date | -| `updated_at` | Timestamp | Last update date | - -#### `trading_analysis.brokerage_accounts` -Cross-reference table for account numbers: - -| Column | Type | Description | -|--------|------|-------------| -| `id` | Primary Key | Account identifier | -| `account_number` | Unique | Brokerage account number | -| `account_display_name` | String | Optional friendly name | -| `user_id` | Foreign Key | Links to users table | -| `is_primary` | Boolean | Primary account flag | -| `created_at` | Timestamp | Creation date | -| `updated_at` | Timestamp | Last update date | - -### Updated Tables - -All existing tables have been updated with a `brokerage_account_id` foreign key: -- `raw_transactions` -- `matched_trades` -- `dividend_transactions` -- `monthly_trading_summary` -- `monthly_dividend_summary` -- `monthly_combined_summary` -- `processing_log` - -## Migration Process - -To migrate an existing database to support multiple users: - -### Step 1: Run the Migration Script - -```bash -python migrate_to_multiuser.py -``` - -### Step 2: Set Environment Variables (optional) - -```bash -export DEFAULT_MIGRATION_EMAIL="your-admin@example.com" -export DEFAULT_MIGRATION_NAME="Admin User" -export DEFAULT_BROKERAGE_ACCOUNT="YOUR_ACCOUNT_NUMBER" -``` - - - The migration script will create default values if these environment variables are not set. - - -### What the Migration Does - - - - Creates `users` and `brokerage_accounts` tables - - - Adds `brokerage_account_id` columns to existing tables - - - Creates a default user and account for existing data - - - Updates all existing transactions to reference the default account - - - Recreates database views to work with the new schema - - - -## Application Changes - -### User Profile Management - - - - Users can now set their brokerage account number in their profile - - - CSV uploads require a valid brokerage account number - - - Users can have multiple brokerage accounts (future feature) - - - Users only see their own transaction data - - - -### Upload Process - -1. **User Validation**: Checks that user has a brokerage account before allowing uploads -2. **Account Association**: All uploaded transactions are associated with the user's account -3. **Processing**: Modified `trading_analysis.py` to accept `--account-id` parameter - -### Authentication Flow - - - - User logs in via Google OAuth - - - User record is created/updated in the database - - - User sets their brokerage account number in profile - - - Brokerage account record is created and linked to user - - - CSV uploads are associated with the user's account - - - -## Database Queries - -### User-Specific Data - -All queries now need to filter by `brokerage_account_id`: - -```sql --- Get user's transactions -SELECT * FROM trading_analysis.raw_transactions rt -JOIN trading_analysis.brokerage_accounts ba ON rt.brokerage_account_id = ba.id -WHERE ba.user_id = ?; - --- Get user's trading performance -SELECT * FROM trading_analysis.v_trading_performance -WHERE user_email = 'user@example.com'; -``` - -### Updated Views - -Views now include user context: - -- `v_current_positions` - Shows account and user information -- `v_trading_performance` - Includes user email and account number - -## Configuration - -### Environment Variables - -```bash -# Migration Configuration -DEFAULT_MIGRATION_EMAIL=your-admin@example.com -DEFAULT_MIGRATION_NAME=Admin User -DEFAULT_BROKERAGE_ACCOUNT=YOUR_ACCOUNT_NUMBER - -# OAuth Configuration (existing) -GOOGLE_CLIENT_ID=your-client-id -GOOGLE_CLIENT_SECRET=your-client-secret -AUTHORIZED_USERS=user1@example.com,user2@example.com -``` - -## Security Considerations - - - User data isolation is critical for multi-user environments. Always verify queries filter by the correct account ID. - - -1. **User Isolation**: Users can only see their own transaction data -2. **Account Validation**: Brokerage account numbers are validated before processing -3. **OAuth Integration**: User authentication is handled by Google OAuth -4. **Data Protection**: User data is isolated by account ID in all database operations - -## Future Enhancements - - - - Support for users with multiple brokerage accounts - - - Allow users to share specific accounts with other users - - - Administrative interface for managing users and accounts - - - User-specific data export functionality - - - -## Troubleshooting - - - - - Ensure database connection is working - - Verify you have proper permissions - - Check for existing foreign key constraints - - Review migration logs for specific errors - - - - - Check that OAuth is configured correctly - - Verify user email is in AUTHORIZED_USERS - - Check application logs for authentication errors - - - - - Verify user has set brokerage account number in profile - - Check CSV format matches expected schema - - Review processing logs in `trading_analysis.log` - - - - - Ensure queries are filtering by correct account ID - - Verify user-account association is correct - - Check database views are updated - - - -### Database Verification - -```sql --- Check user-account associations -SELECT u.email, u.brokerage_account_number, ba.account_number, ba.is_primary -FROM trading_analysis.users u -LEFT JOIN trading_analysis.brokerage_accounts ba ON u.id = ba.user_id; - --- Check transaction associations -SELECT COUNT(*) as transaction_count, ba.account_number, u.email -FROM trading_analysis.raw_transactions rt -JOIN trading_analysis.brokerage_accounts ba ON rt.brokerage_account_id = ba.id -JOIN trading_analysis.users u ON ba.user_id = u.id -GROUP BY ba.account_number, u.email; -``` - -## Next Steps - - - - Set up portfolio tracking for your account - - - Learn how to upload transaction data - - diff --git a/guides/setup/sso.mdx b/guides/setup/sso.mdx deleted file mode 100644 index 0b34b00..0000000 --- a/guides/setup/sso.mdx +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: 'SSO Authentication Setup' -description: 'Configure Google OAuth 2.0 authentication for your Trading Analysis Dashboard' ---- - -## Overview - -This guide will help you configure Google OAuth 2.0 authentication for secure access to your Trading Analysis Dashboard. - -## Step 1: Create Google OAuth Application - - - - Visit [Google Cloud Console](https://console.cloud.google.com/) and sign in with your Google account - - - - - Click "Select a project" → "New Project" - - Name: "Trading Dashboard" - - Click "Create" - - - - - Go to "APIs & Services" → "Library" - - Search for "Google+ API" and enable it - - Also enable "Google Identity" if available - - - - - Go to "APIs & Services" → "Credentials" - - Click "Create Credentials" → "OAuth 2.0 Client IDs" - - Choose "Web application" - - Name: "Trading Dashboard Auth" - - - - Add the following URLs: - - **Authorized JavaScript origins:** - - `https://performance.miningwood.com` - - `http://localhost:8080` (for testing) - - **Authorized redirect URIs:** - - `https://performance.miningwood.com/auth/callback` - - `http://localhost:8080/auth/callback` (for testing) - - - - Copy the "Client ID" and "Client Secret" for the next step - - - -## Step 2: Configure Environment Variables - -Update your `.env.docker` file with the OAuth credentials: - -```bash .env.docker -# OAuth Configuration -GOOGLE_CLIENT_ID=your-actual-client-id.apps.googleusercontent.com -GOOGLE_CLIENT_SECRET=your-actual-client-secret - -# Authorized Users (your email addresses) -AUTHORIZED_USERS=your-email@gmail.com,admin@company.com -``` - - - Never commit your `.env` files to version control. Keep them secure and out of your repository. - - -## Step 3: Update and Deploy - -### Rebuild the application - -```bash -docker compose build trading_app -docker compose restart trading_app -``` - -### Test the authentication - - - - Navigate to `https://performance.miningwood.com` - - - - You should be redirected to the login page. Click "Sign in with Google" - - - - Authorize the application when prompted by Google - - - - You should be redirected back and logged in successfully - - - -## Security Features - - - - Industry standard authentication protocol - - - Only specific email addresses can access - - - Secure server-side sessions with expiration - - - All authentication over encrypted connections - - - -## User Management - -### Add Users - -Add email addresses to `AUTHORIZED_USERS` in `.env.docker`, separated by commas: - -```bash -AUTHORIZED_USERS=user1@example.com,user2@example.com,user3@example.com -``` - -Then restart the application: - -```bash -docker compose restart trading_app -``` - -### Remove Users - -Remove email addresses from `AUTHORIZED_USERS` and restart the application. - - - Leave `AUTHORIZED_USERS` empty to allow all users (not recommended for production) - - -## Troubleshooting - - - - - Check that Client ID and Secret are correct in `.env.docker` - - Verify redirect URLs match exactly in Google Cloud Console - - Ensure Google+ API is enabled - - Check application logs: `docker compose logs trading_app` - - - - - Verify your email is in `AUTHORIZED_USERS` - - Ensure email case matches exactly - - Check for extra spaces in the email list - - - - - Clear browser cookies for your domain - - Verify Flask secret key is set in `.env.docker` - - Check session configuration in application logs - - - - Ensure the redirect URIs in Google Cloud Console match your deployment: - - Use `https://` for production - - Include the exact domain and path - - No trailing slashes - - - -## Alternative OAuth Providers - -You can also configure other OAuth providers: - - - - ```bash .env.docker - GITHUB_CLIENT_ID=your-github-client-id - GITHUB_CLIENT_SECRET=your-github-client-secret - ``` - - 1. Create OAuth App at https://github.com/settings/developers - 2. Set Authorization callback URL to `https://your-domain.com/auth/callback` - - - - ```bash .env.docker - MICROSOFT_CLIENT_ID=your-microsoft-client-id - MICROSOFT_CLIENT_SECRET=your-microsoft-client-secret - ``` - - 1. Register app at https://portal.azure.com - 2. Add redirect URI in Authentication settings - - - - - Contact your administrator if you need help configuring alternative providers. - - -## Testing OAuth Configuration - -To test your OAuth setup locally: - -```bash -# Start the application locally -docker compose up -d - -# Check logs for any OAuth errors -docker compose logs -f trading_app - -# Visit localhost -open http://localhost:8080 -``` - -## Security Checklist - -- [ ] OAuth credentials are stored in `.env` files, not in code -- [ ] `.env` files are in `.gitignore` -- [ ] `AUTHORIZED_USERS` list is properly configured -- [ ] HTTPS is enabled in production -- [ ] Strong `FLASK_SECRET_KEY` is set -- [ ] Redirect URIs are exact matches in Google Cloud Console -- [ ] Google+ API is enabled - -## Next Steps - - - - Configure multi-user support with brokerage accounts - - - Deploy your application to production - - diff --git a/index.mdx b/index.mdx index d63e3a9..b287a86 100644 --- a/index.mdx +++ b/index.mdx @@ -1,26 +1,26 @@ --- title: "Trading Analysis Dashboard" -description: "A comprehensive platform for analyzing trading performance and managing your investment portfolio" +description: "Documentation for a comprehensive platform to analyze trading performance and manage investment portfolios" --- -## Welcome to Trading Analysis Dashboard +## Overview -A modern, interactive web application for tracking and analyzing your stock trading performance with real-time portfolio management and comprehensive reporting. +This documentation covers the Trading Analysis Dashboard - a Flask-based web application for tracking stock trading performance with real-time portfolio management and comprehensive reporting capabilities. - Get up and running in minutes with our quick start guide + Learn about the application's purpose and architecture - Track your holdings with real-time price updates from Finnhub + Track holdings with real-time price updates from Finnhub - Integrate with our comprehensive RESTful API + Explore the RESTful API endpoints -## Key Features +## Core Features - Track your stock, ETF, and mutual fund holdings with real-time price updates from Finnhub. View allocation charts, performance metrics, and gain/loss analysis. + Track stock, ETF, and mutual fund holdings with real-time price updates from Finnhub. View allocation charts, performance metrics, and gain/loss analysis with automatic price refresh capabilities. - Analyze monthly trading performance with detailed P&L breakdowns, win/loss ratios, and trade-by-trade analysis. View comprehensive reports with dividend tracking. + Analyze monthly trading performance with detailed P&L breakdowns, win/loss ratios, and trade-by-trade analysis. Includes comprehensive reports with dividend tracking and hybrid matching algorithm for broker-level accuracy. - - Google OAuth 2.0 integration with user-specific data isolation. Support for multiple users with separate brokerage accounts. + + Google OAuth 2.0 integration with user-specific data isolation. Support for multiple users with separate brokerage accounts and authorized user controls. - - Easy CSV import with drag-and-drop support. Real-time processing feedback and upload history tracking. + + Import transaction history and holdings via CSV with drag-and-drop support. Real-time processing feedback and upload history tracking for portfolio and trading data. - - Complete Docker Compose setup with PostgreSQL database, Caddy reverse proxy, and automatic HTTPS with Let's Encrypt. + + Analyze trading performance across custom date ranges. Compare periods, track trends, and generate reports for specific timeframes. - - Full Gitea Actions workflow for automated testing, building, and deployment with security scanning and rollback capabilities. + + View trading activity calendar with monthly heat maps showing P&L by day. Quickly identify patterns and peak trading periods. -## Technology Stack +## Application Architecture - Python web framework + Python web framework for backend API and page rendering - Relational database + Relational database for user data, trades, and holdings - - Containerization + + Frontend UI framework with custom styling - - Reverse proxy & HTTPS - - - Real-time market data + + Real-time market data integration - Secure authentication + Secure Google authentication + + + Interactive data visualizations -## Getting Started +## Key Concepts - - - Install Docker and Docker Compose, and obtain a Finnhub API key - - - Clone the repository and set up your environment variables - - - Run the deployment script to start all services - - - Import your trading data via CSV upload - - +### Hybrid Matching Algorithm + +The trading analysis uses a hybrid matching system that combines broker-provided realized gains/losses with transaction history to achieve broker-level accuracy for closed positions. See [Hybrid Matching](/features/hybrid-matching) for details. + +### Multi-User Support + +The application supports multiple users with isolated data. Each user can have separate brokerage accounts and portfolios, with data access controlled by OAuth authentication. + +### Real-Time Price Updates + +Portfolio holdings are updated with real-time prices from Finnhub API, with intelligent rate limiting and caching to stay within API quotas while providing fresh data. - Check out our comprehensive quickstart guide to get your dashboard running in minutes + Read the application overview to understand how everything works together diff --git a/quickstart.mdx b/quickstart.mdx index 9b372bc..907b1df 100644 --- a/quickstart.mdx +++ b/quickstart.mdx @@ -1,205 +1,207 @@ --- -title: "Quickstart" -description: "Get your Trading Analysis Dashboard up and running in minutes" +title: "Application Overview" +description: "Understanding the Trading Analysis Dashboard and its components" --- -## Get Started in Four Steps +## What is the Trading Analysis Dashboard? -Deploy your trading analysis dashboard and start tracking your portfolio performance. +The Trading Analysis Dashboard is a Flask-based web application designed to track and analyze stock trading performance. It provides real-time portfolio management, historical trade analysis, and comprehensive reporting to help understand trading patterns and portfolio performance. -### Step 1: Prerequisites +## Core Components - - Install [Docker Desktop](https://www.docker.com/products/docker-desktop/) which includes Docker Compose. This is required for running the application containers. - - - 1. Register for a free account at [Finnhub.io](https://finnhub.io/register) - 2. Navigate to your dashboard - 3. Copy your API key - you'll need this for real-time price updates + + Tracks current holdings including stocks, ETFs, and mutual funds with real-time price updates from Finnhub API. Displays allocation charts, performance metrics, and gain/loss analysis. - The free tier includes 60 API calls per minute and real-time US stock quotes + **Key capabilities:** + - Add/edit/delete holdings + - Real-time price refresh + - Allocation visualization + - Performance tracking - - For secure authentication, create OAuth credentials: - 1. Visit [Google Cloud Console](https://console.cloud.google.com/) - 2. Create a new project - 3. Enable Google+ API - 4. Create OAuth 2.0 credentials - 5. Copy Client ID and Client Secret + + + Analyzes historical trading performance using a hybrid matching algorithm that combines broker-provided realized gains/losses with transaction history for broker-level accuracy. - See the [SSO Setup Guide](/guides/setup/sso) for detailed instructions. + **Key capabilities:** + - Monthly P&L breakdown + - Trade-by-trade details + - Win/loss ratios + - Dividend tracking + + + + Allows custom date range analysis to compare trading performance across different periods and identify trends. + + **Key capabilities:** + - Custom date ranges + - Period comparison + - Trend identification + - Performance reports + + + + Visual calendar view showing daily trading activity with heat maps to quickly identify profitable and losing periods. + + **Key capabilities:** + - Monthly calendar view + - P&L heat mapping + - Pattern recognition + - Activity tracking + + + + Supports bulk data import via CSV files for both portfolio holdings and transaction history with drag-and-drop interface. + + **Key capabilities:** + - Drag-and-drop upload + - Real-time processing feedback + - Upload history tracking + - Format validation -### Step 2: Configure Environment +## Application Flow - - - ```bash - git clone https://your-repo-url/trading-analysis-dashboard.git - cd trading-analysis-dashboard - ``` - - - - ```bash - cp .env.docker .env - ``` - - - - Update the following values: - - ```env .env - # Finnhub Configuration - FINNHUB_API_KEY=your_finnhub_api_key_here - - # Database Configuration - POSTGRES_PASSWORD=choose_secure_password - - # Flask Configuration - FLASK_SECRET_KEY=generate_random_secret_key - - # OAuth Configuration (Optional) - GOOGLE_CLIENT_ID=your_google_client_id - GOOGLE_CLIENT_SECRET=your_google_client_secret - AUTHORIZED_USERS=your-email@example.com - ``` - - Never commit the `.env` file to version control! - - +### User Authentication -### Step 3: Deploy +The application uses Google OAuth 2.0 for secure authentication. Users must be authorized (configured in environment variables) to access the system. Each user's data is completely isolated. - - - ```batch - deploy.bat - ``` - - - ```bash - chmod +x deploy.sh - ./deploy.sh - ``` - - - ```bash - docker compose up -d - docker compose ps - ``` - - +```mermaid +graph LR + A[User] --> B[Login Page] + B --> C{OAuth 2.0} + C -->|Authorized| D[Dashboard] + C -->|Unauthorized| E[Access Denied] +``` - - Wait for all containers to start. This may take a minute for first-time setup. - +### Data Structure -### Step 4: Access and Configure +The application maintains three primary data entities: - - - Navigate to `http://localhost:8080` in your browser - - - - Click "Sign in with Google" and authorize the application - - - - Add your brokerage account number in the profile page - - - - Go to the Upload page and import your CSV transaction history - - +| Entity | Description | Key Fields | +|--------|-------------|------------| +| **Users** | Authentication and profile | email, brokerage_account, google_id | +| **Holdings** | Current portfolio positions | symbol, shares, cost_basis, current_price | +| **Transactions** | Historical trading activity | symbol, action, shares, price, date | -## Next Steps +### Hybrid Matching Algorithm -Now that your dashboard is running, explore these features: +The trading analysis uses a sophisticated matching system: + +1. **Broker Realized Gains/Losses** - Pre-calculated lot matches from broker statements provide definitive P/L for closed positions +2. **Transaction History** - Complete buy/sell transaction records for verification and detail +3. **Hybrid Approach** - Combines both sources to achieve broker-level accuracy while maintaining transaction-level detail + +See [Hybrid Matching](/features/hybrid-matching) for technical details. + +## API Architecture + +The application exposes a RESTful API with the following endpoint categories: - - - Add your holdings and track real-time performance - - - - Import your trading history from your broker - - - - Analyze monthly trading performance and P&L - - - - Integrate with the REST API - - + + Access monthly trading data, individual trades, and P/L information + + + Manage holdings and trigger price refresh operations + + + OAuth endpoints and session management + + + Query performance across custom date ranges + -## Common Tasks +## Technology Stack -### View Logs +### Backend +- **Flask** - Python web framework handling routing, templating, and business logic +- **SQLAlchemy** - ORM for database operations +- **PostgreSQL** - Relational database for data persistence +- **Flask-Dance** - OAuth integration for Google authentication -```bash -# All services -docker compose logs -f +### Frontend +- **Bootstrap 5** - Responsive UI framework +- **Chart.js** - Interactive charts and visualizations +- **jQuery** - DOM manipulation and AJAX requests +- **DataTables** - Enhanced table functionality -# Specific service -docker compose logs -f trading_app +### External Services +- **Finnhub API** - Real-time stock price data +- **Google OAuth 2.0** - User authentication + +## Data Models + +### Portfolio Holdings + +```python +class Holding: + id: int + user_id: int + symbol: str + shares: float + average_cost: float + type: str # stock, etf, mutual_fund + current_price: float + last_updated: datetime ``` -### Restart Services +### Trading Transactions -```bash -docker compose restart +```python +class Transaction: + id: int + user_id: int + symbol: str + action: str # buy, sell + shares: int + price: float + date: datetime + account_number: str ``` -### Update Application +### Realized Gains -```bash -docker compose pull -docker compose up -d +```python +class RealizedGain: + id: int + user_id: int + symbol: str + date_acquired: datetime + date_sold: datetime + proceeds: float + cost_basis: float + gain_loss: float ``` -### Backup Database +## Configuration -```bash -docker compose exec postgres pg_dump -U trading_user mining_wood > backup.sql -``` +The application is configured via environment variables: -## Troubleshooting +| Variable | Purpose | +|----------|---------| +| `FINNHUB_API_KEY` | API key for price data | +| `GOOGLE_CLIENT_ID` | OAuth client ID | +| `GOOGLE_CLIENT_SECRET` | OAuth client secret | +| `AUTHORIZED_USERS` | Comma-separated email list | +| `FLASK_SECRET_KEY` | Session encryption key | +| `DATABASE_URL` | PostgreSQL connection string | - - - Check the logs for errors: - ```bash - docker compose logs trading_app - ``` - - Common issues: - - Missing environment variables - - Database connection failure - - Port 8080 already in use - - - - - Verify OAuth credentials are correct in `.env` - - Check that your email is in `AUTHORIZED_USERS` - - Clear browser cookies and try again - - - - - Verify `FINNHUB_API_KEY` is set correctly - - Check API quota hasn't been exceeded - - Review application logs for API errors - - +## Features Deep Dive - - **Need help?** Check our [deployment guide](/guides/deployment/docker) or [setup guides](/guides/setup/cicd) for more detailed instructions. - + + + Learn about tracking holdings and price updates + + + Understand P&L calculations and reporting + + + Import data from your broker + + + How the matching algorithm works + +