Security Guide

Last Updated: December 2025
Status: Security Best Practices

This guide covers security best practices, API key management, and security considerations for the Trading System.

Overview

Security is paramount in trading systems, especially when handling API keys, financial data, and system access. This guide provides comprehensive security practices for protecting your trading system.

API Key Management

Environment Variables

Never commit API keys to version control. Always use environment variables stored in .env files that are excluded from Git.

Best Practices

  1. Use .env Files:

    # Add to .gitignore
    .env
    .env.local
    .env.*.local
    

  2. Template Files:

  3. Keep deployment/env.example as a template
  4. Never include actual keys in example files
  5. Use placeholder values

  6. Environment Variable Security:

    # Good: Use strong, unique keys
    ALPACA_API_KEY=your_api_key_here
    ALPACA_SECRET_KEY=your_secret_key_here
    
    # Set proper file permissions (Linux/Mac)
    chmod 600 .env
    

API Key Rotation

  • Regular Rotation: Rotate API keys periodically (every 90 days recommended)
  • Immediate Revocation: Revoke keys immediately if compromised
  • Separate Keys: Use different keys for development, staging, and production
  • Paper Trading First: Always use paper trading API keys for testing

Alpaca API Keys

  1. Account Security:
  2. Enable two-factor authentication (2FA) on your Alpaca account
  3. Use paper trading keys for development
  4. Limit API key permissions when possible

  5. Key Storage:

    # Store in .env file (not in code)
    ALPACA_API_KEY=PKxxxxxxxxxxxxx
    ALpACA_SECRET_KEY=xxxxxxxxxxxxxxxxxxxx
    ALPACA_BASE_URL=https://paper-api.alpaca.markets
    

  6. Key Validation:

  7. Never share API keys in logs or error messages
  8. Mask keys in debug output
  9. Validate keys before use

Polygon.io API Keys

  1. Key Management:

    POLYGON_API_KEY=your_polygon_key
    

  2. Rate Limiting:

  3. Respect rate limits to avoid key revocation
  4. Monitor API usage
  5. Implement backoff strategies

Database Security

Connection Security

  1. Strong Passwords:
  2. Use complex passwords for PostgreSQL users
  3. Change default passwords immediately
  4. Use password managers

  5. Connection Strings:

    # Use environment variables, never hardcode
    POSTGRES_URL=postgresql://user:password@localhost:5432/trading_system
    

  6. SSL/TLS:

  7. Enable SSL for production databases
  8. Use connection pooling securely
  9. Restrict database access by IP when possible

Database Access Control

  1. User Permissions:
  2. Use least-privilege principle
  3. Create separate users for different services
  4. Revoke unnecessary permissions

  5. Schema Isolation:

  6. Use schema-based isolation (already implemented)
  7. Limit cross-schema access
  8. Use row-level security (RLS) when appropriate

Application Security

Code Security

  1. Dependencies:
  2. Regularly update dependencies
  3. Check for known vulnerabilities: pip audit
  4. Use pinned versions in requirements.txt

  5. Input Validation:

  6. Validate all user inputs
  7. Use Pydantic models for data validation
  8. Sanitize inputs before database queries

  9. SQL Injection Prevention:

  10. Always use parameterized queries (SQLAlchemy ORM does this)
  11. Never concatenate user input into SQL queries
  12. Use ORM methods instead of raw SQL when possible

Authentication & Authorization

  1. API Authentication (Future):
  2. Implement API key authentication for production
  3. Use JWT tokens for user sessions
  4. Implement rate limiting

  5. Streamlit Security:

  6. Run Streamlit on localhost for development
  7. Use authentication for production deployments
  8. Enable HTTPS for production

Secrets Management

  1. Configuration Files:
  2. Never commit secrets to Git
  3. Use environment variables
  4. Consider using secrets management services for production

  5. Logging:

  6. Never log API keys or secrets
  7. Sanitize sensitive data in logs
  8. Use log levels appropriately

Network Security

Local Deployment

  1. Firewall:
  2. Restrict database ports (5432) to localhost
  3. Use Redis authentication
  4. Limit service exposure

  5. Port Security:

  6. Run services on localhost when possible
  7. Use reverse proxy for production
  8. Enable HTTPS for external access

API Security

  1. HTTPS:
  2. Always use HTTPS for production
  3. Validate SSL certificates
  4. Use strong ciphers

  5. CORS:

  6. Configure CORS properly for FastAPI
  7. Restrict allowed origins
  8. Use appropriate headers

Data Security

Data Encryption

  1. At Rest:
  2. Enable PostgreSQL encryption at rest
  3. Encrypt backups
  4. Secure file storage

  5. In Transit:

  6. Use HTTPS/TLS for all connections
  7. Use encrypted database connections
  8. Secure WebSocket connections

Data Privacy

  1. Personal Information:
  2. Minimize data collection
  3. Follow GDPR/privacy regulations
  4. Secure user data

  5. Trading Data:

  6. Protect trading strategies
  7. Secure historical data
  8. Control data access

Best Practices Summary

Do's ✅

  • ✅ Store all secrets in environment variables
  • ✅ Use .env files excluded from Git
  • ✅ Rotate API keys regularly
  • ✅ Use paper trading keys for development
  • ✅ Enable 2FA on all accounts
  • ✅ Keep dependencies updated
  • ✅ Use strong passwords
  • ✅ Validate all inputs
  • ✅ Log errors, not secrets
  • ✅ Use HTTPS for production

Don'ts ❌

  • ❌ Never commit API keys to Git
  • ❌ Don't hardcode secrets in code
  • ❌ Don't share API keys
  • ❌ Don't log sensitive information
  • ❌ Don't use production keys for development
  • ❌ Don't disable security features
  • ❌ Don't ignore security warnings
  • ❌ Don't use default passwords
  • ❌ Don't expose services unnecessarily
  • ❌ Don't skip input validation

Incident Response

If API Keys Are Compromised

  1. Immediate Actions:
  2. Revoke compromised keys immediately
  3. Generate new keys
  4. Review recent API activity
  5. Check for unauthorized trades

  6. Prevention:

  7. Review access logs
  8. Update security practices
  9. Notify affected services

Security Monitoring

  1. Log Monitoring:
  2. Monitor for authentication failures
  3. Watch for unusual API activity
  4. Check database access logs

  5. Alerts:

  6. Set up alerts for failed logins
  7. Monitor API rate limit violations
  8. Track unusual trading activity

Additional Resources


Important: Security is an ongoing process. Regularly review and update your security practices. When in doubt, err on the side of caution.