Skip to content

yrpatil/BrainTransactionsManager

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

14 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ™ BrainTransactionsManager v2.0.0

Blessed by Goddess Laxmi for Infinite Abundance

πŸš€ What's New in v2.0.0

A complete rewrite following SRM Principles (Simple, Reliable, Maintainable):

✨ Key Features

  • πŸ”§ 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

πŸ—οΈ Architecture Overview

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    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  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸš€ Quick Start

1. Environment Setup

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # Linux/Mac
# .venv\Scripts\activate   # Windows

# Install dependencies
pip install -r requirements.txt

2. Configuration

# 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"

3. Database Setup

# 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

4. Start Server

# Development mode
python server.py

# Or with uvicorn
uvicorn server:app --host 127.0.0.1 --port 8000 --reload

5. Test API

# 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}'

πŸ“š API Documentation

Core Endpoints

Method Endpoint Description
GET /health Basic health check
GET /health/detailed Comprehensive system health
GET /config/status Configuration status

Trading Endpoints

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

Portfolio Endpoints

Method Endpoint Description
GET /portfolio/positions Get positions
GET /portfolio/account Get account info

Market Data

Method Endpoint Description
GET /market/data/{symbol} Get market data
GET /exchanges Get supported exchanges

βš™οΈ Configuration

Environment Files

  • config/development.yaml - Development settings
  • config/production.yaml - Production settings
  • config/testing.yaml - Test settings

Environment Variables

# 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=INFO

Configuration Structure

database:
  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

πŸ§ͺ Testing

Run Tests

# 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

Test Categories

  • Unit Tests: Individual component testing
  • Integration Tests: Multi-component interactions
  • Performance Tests: Response time and throughput
  • Error Handling: Edge cases and failure modes

πŸ—„οΈ Database Management

Migrations

# Check migration status
curl http://localhost:8000/migrations/status

# Run pending migrations
curl -X POST http://localhost:8000/migrations/run

Manual Migration Commands

# Using Alembic directly
cd api_versions/v2.0.0/migrations
alembic current
alembic upgrade head
alembic downgrade -1

πŸ“Š Monitoring

Background Tasks

The 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

Monitoring Status

# Get monitoring status
curl http://localhost:8000/health/detailed

πŸ”’ Security Features

Production Security

  • Environment Variables: No hardcoded secrets
  • CORS Configuration: Configurable origins
  • Rate Limiting: API request throttling
  • Input Validation: Pydantic model validation
  • Error Masking: Production error handling

Development vs Production

Feature Development Production
Paper Trading βœ… Default ⚠️ Configurable
Debug Logging βœ… Enabled ❌ INFO only
Error Details βœ… Full stack ❌ Generic messages
CORS Origins localhost Configured domains

πŸš€ Deployment

Production Checklist

  • Set ENVIRONMENT=production
  • Configure production database
  • Set real Alpaca credentials
  • Configure CORS origins
  • Set up log aggregation
  • Configure monitoring alerts
  • Review security settings

Docker Deployment (Future)

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"]

πŸ”§ Development

Code Structure

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

Adding New Exchanges

  1. Create adapter class extending MarketAdapter
  2. Implement required methods
  3. Register in ExchangeManager
  4. Add configuration section
  5. Write tests

Adding New Features

  1. Follow SRM principles (Simple, Reliable, Maintainable)
  2. Add configuration options
  3. Write comprehensive tests
  4. Update documentation
  5. Consider monitoring implications

πŸ“ˆ Performance

Benchmarks

  • Configuration Loading: < 100ms
  • API Response Time: < 100ms (target)
  • Database Queries: < 50ms (typical)
  • Order Placement: < 500ms

Optimization

  • Connection Pooling: Database connection reuse
  • Background Tasks: Async processing
  • Caching: Configuration and metadata caching
  • Batch Operations: Bulk database updates

πŸ› Troubleshooting

Common Issues

Database Connection Failed

# Check PostgreSQL status
brew services list | grep postgres
sudo systemctl status postgresql

# Check configuration
curl http://localhost:8000/health/detailed

Alpaca API Errors

# Verify credentials
echo $ALPACA_API_KEY
echo $ALPACA_SECRET_KEY

# Check account status
curl http://localhost:8000/portfolio/account

Migration Issues

# Check migration status
curl http://localhost:8000/migrations/status

# Manual migration
cd migrations && alembic upgrade head

🀝 Contributing

Development Workflow

  1. Create feature branch
  2. Follow SRM principles
  3. Write tests
  4. Update documentation
  5. Submit pull request

Code Standards

  • 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

πŸ™ Acknowledgments

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! ✨

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •