Blessed by Goddess Laxmi for Infinite Abundance
A complete rewrite following SRM Principles (Simple, Reliable, Maintainable):
- π§ Unified Configuration: Single YAML file with environment overrides
- ποΈ Enhanced Database: Startup validation, health checks, and migration system
- π Multi-Exchange Support: Alpaca stocks and crypto via unified adapter
- π Smart Monitoring: Background polling for KPIs and portfolio sync
- π‘οΈ Production Ready: Security hardening, error handling, and logging
- π§ͺ Comprehensive Testing: Unit, integration, and performance tests
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FastAPI Server v2.0.0 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Configuration β Exchange Manager β Background Monitor β
β - YAML Config β - Alpaca Adapter β - Price Updates β
β - Env Override β - Multi-Asset β - Portfolio Sync β
β - Validation β - Auto-Routing β - Order Reconcile β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Database Layer + Migrations β
β - PostgreSQL β - Health Checks β - Alembic Migrationsβ
β - Connection β - Startup Valid. β - Schema Evolution β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # Linux/Mac
# .venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txt# Copy environment template
cp config/development.yaml config/local.yaml
# Set environment variables
export ALPACA_API_KEY="your_api_key"
export ALPACA_SECRET_KEY="your_secret_key"
export ENVIRONMENT="development"# Ensure PostgreSQL is running
brew services start postgresql # Mac
sudo systemctl start postgresql # Linux
# Run database setup (if not already done)
psql -U $(whoami) postgres -f ../../database/ddl/setup_complete.sql# Development mode
python server.py
# Or with uvicorn
uvicorn server:app --host 127.0.0.1 --port 8000 --reload# Health check
curl http://localhost:8000/health
# Detailed health
curl http://localhost:8000/health/detailed
# Get account info
curl http://localhost:8000/portfolio/account
# Place a buy order (paper trading)
curl -X POST http://localhost:8000/buy \
-H "Content-Type: application/json" \
-d '{"symbol": "AAPL", "quantity": 1}'| Method | Endpoint | Description |
|---|---|---|
GET |
/health |
Basic health check |
GET |
/health/detailed |
Comprehensive system health |
GET |
/config/status |
Configuration status |
| Method | Endpoint | Description |
|---|---|---|
POST |
/orders |
Place order |
GET |
/orders |
Get orders |
GET |
/orders/{id} |
Get order status |
DELETE |
/orders/{id} |
Cancel order |
POST |
/buy |
Quick buy order |
POST |
/sell |
Quick sell order |
POST |
/close/{symbol} |
Close position |
| Method | Endpoint | Description |
|---|---|---|
GET |
/portfolio/positions |
Get positions |
GET |
/portfolio/account |
Get account info |
| Method | Endpoint | Description |
|---|---|---|
GET |
/market/data/{symbol} |
Get market data |
GET |
/exchanges |
Get supported exchanges |
config/development.yaml- Development settingsconfig/production.yaml- Production settingsconfig/testing.yaml- Test settings
# Required
ALPACA_API_KEY=your_api_key
ALPACA_SECRET_KEY=your_secret_key
# Optional
ENVIRONMENT=development
DB_HOST=localhost
DB_PORT=5432
DB_NAME=braintransactions
LOG_LEVEL=INFOdatabase:
host: localhost
pool_size: 10
trading:
paper_trading: true
max_position_size_percent: 10.0
alpaca:
api_key: ${ALPACA_API_KEY}
base_url: https://paper-api.alpaca.markets
security:
cors_origins: ["http://localhost:3000"]
api_rate_limit: 1000
monitoring:
price_poll_interval: 60
portfolio_sync_interval: 300# All tests
pytest
# Specific test categories
pytest -m "not integration" # Unit tests only
pytest -m integration # Integration tests
pytest -m performance # Performance tests
# With coverage
pytest --cov=src/braintransactions --cov-report=html- Unit Tests: Individual component testing
- Integration Tests: Multi-component interactions
- Performance Tests: Response time and throughput
- Error Handling: Edge cases and failure modes
# Check migration status
curl http://localhost:8000/migrations/status
# Run pending migrations
curl -X POST http://localhost:8000/migrations/run# Using Alembic directly
cd api_versions/v2.0.0/migrations
alembic current
alembic upgrade head
alembic downgrade -1The system runs several background monitoring tasks:
- Price Updates: Updates market data every 60s
- Portfolio Sync: Reconciles positions every 5m
- Order Reconciliation: Updates order statuses every 30s
- KPI Calculation: Calculates performance metrics every 5m
- Health Checks: System health monitoring every 30s
# Get monitoring status
curl http://localhost:8000/health/detailed- Environment Variables: No hardcoded secrets
- CORS Configuration: Configurable origins
- Rate Limiting: API request throttling
- Input Validation: Pydantic model validation
- Error Masking: Production error handling
| Feature | Development | Production |
|---|---|---|
| Paper Trading | β Default | |
| Debug Logging | β Enabled | β INFO only |
| Error Details | β Full stack | β Generic messages |
| CORS Origins | localhost |
Configured domains |
- Set
ENVIRONMENT=production - Configure production database
- Set real Alpaca credentials
- Configure CORS origins
- Set up log aggregation
- Configure monitoring alerts
- Review security settings
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8000"]api_versions/v2.0.0/
βββ src/braintransactions/
β βββ core/ # Configuration, exceptions, monitoring
β βββ database/ # Connection, migrations
β βββ markets/ # Exchange adapters
β βββ __init__.py
βββ config/ # Environment configurations
βββ tests/ # Test suite
βββ server.py # FastAPI application
βββ requirements.txt
- Create adapter class extending
MarketAdapter - Implement required methods
- Register in
ExchangeManager - Add configuration section
- Write tests
- Follow SRM principles (Simple, Reliable, Maintainable)
- Add configuration options
- Write comprehensive tests
- Update documentation
- Consider monitoring implications
- Configuration Loading: < 100ms
- API Response Time: < 100ms (target)
- Database Queries: < 50ms (typical)
- Order Placement: < 500ms
- Connection Pooling: Database connection reuse
- Background Tasks: Async processing
- Caching: Configuration and metadata caching
- Batch Operations: Bulk database updates
Database Connection Failed
# Check PostgreSQL status
brew services list | grep postgres
sudo systemctl status postgresql
# Check configuration
curl http://localhost:8000/health/detailedAlpaca API Errors
# Verify credentials
echo $ALPACA_API_KEY
echo $ALPACA_SECRET_KEY
# Check account status
curl http://localhost:8000/portfolio/accountMigration Issues
# Check migration status
curl http://localhost:8000/migrations/status
# Manual migration
cd migrations && alembic upgrade head- Create feature branch
- Follow SRM principles
- Write tests
- Update documentation
- Submit pull request
- Type Hints: All function parameters and returns
- Docstrings: Clear function documentation
- Error Handling: Comprehensive exception handling
- Testing: Unit and integration tests
- Logging: Structured logging with context
Built with gratitude and blessed by Goddess Laxmi for infinite abundance and prosperity in trading endeavors.
May your trades be profitable and your systems be reliable! β¨