A full-stack web application that enables traders and quantitative analysts to develop, test, and analyze algorithmic trading strategies with real market data. Built with modern technologies and production-ready architecture.
| Feature | Description |
|---|---|
| 🎨 No Coding Required | Use pre-built strategy templates with visual configuration |
| 🔌 Multi-Broker Support | Integrate with Binance, Zerodha, and more |
| 📊 Real-Time Data | Test with both historical and real-time market data |
| 📈 Advanced Analytics | Sharpe ratio, drawdown analysis, win rate, and more |
| 🔒 Secure & Scalable | JWT authentication, PostgreSQL database, cloud-ready |
| ⚡ Production-Ready | Built with FastAPI, Next.js, and enterprise patterns |
# Clone the repository
git clone <your-repo-url>
cd Backtesting_Engine-main
# Backend setup
cd backend
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt
uvicorn main:app --reload
# Frontend setup (in new terminal)
cd frontend
npm install
npm run dev📖 Complete Guide: START_HERE.md | ☁️ Deploy in 5 min: QUICK_DEPLOY.md
Live Demo: [Coming Soon]
Video Walkthrough: [Coming Soon]
Click to view screenshots
Add screenshot: Dashboard with portfolio overview and recent backtests
Add screenshot: Monaco Editor with strategy code
Add screenshot: Performance charts and metrics
- Overview
- Demo
- Features
- Tech Stack
- Architecture
- Installation
- Usage
- API Documentation
- Strategy Development
- Deployment
- Testing
- Documentation
- Roadmap
- Contributing
- Support
|
|
📦 Complete Technology Breakdown
- Framework: FastAPI 0.104+ (async support, automatic docs)
- Language: Python 3.13+ (type hints, modern features)
- Database: PostgreSQL 14+ with SQLAlchemy 2.0 ORM
- Authentication: JWT (python-jose) with bcrypt hashing
- HTTP Clients: httpx, aiohttp for async broker APIs
- Validation: Pydantic v2 for data validation
- Server: Uvicorn (high-performance ASGI server)
- Framework: Next.js 16.1 with App Router
- Language: TypeScript 5.0+ (strict mode)
- UI Library: React 19.2 with server components
- Styling: Tailwind CSS 4.0 (utility-first)
- Components: Radix UI primitives (accessible)
- Code Editor: Monaco Editor (VS Code engine)
- Charts: Recharts (responsive charts)
- HTTP Client: Axios with interceptors
- Icons: Lucide React (optimized icons)
- Frontend Hosting: Vercel (serverless, CDN)
- Backend Hosting: Railway/Render (containers)
- Database: Managed PostgreSQL (Render/Railway/Supabase)
- Containerization: Docker & Docker Compose
- CI/CD: GitHub Actions (optional)
- Monitoring: Built-in health checks
graph TB
subgraph "Frontend Layer"
A[Next.js App Router]
B[Dashboard UI]
C[Strategy Editor]
D[Backtest Results]
end
subgraph "Backend Layer"
E[FastAPI Server]
F[Auth Module]
G[Strategy Manager]
H[Backtest Engine]
I[Broker Factory]
end
subgraph "Data Layer"
J[(PostgreSQL)]
K[Users]
L[Strategies]
M[Backtests]
end
subgraph "External Services"
N[Binance API]
O[Other Brokers]
end
A --> E
B --> E
C --> E
D --> E
E --> F
E --> G
E --> H
E --> I
F --> J
G --> J
H --> J
I --> N
I --> O
J --> K
J --> L
J --> M
| Pattern | Implementation | Purpose |
|---|---|---|
| Event-Driven | Backtesting Engine | Realistic market simulation |
| Factory Pattern | Broker integrations | Unified multi-broker interface |
| Repository Pattern | Database abstraction | Clean separation of concerns |
| Strategy Pattern | Base strategy class | Extensible strategy framework |
| Middleware | JWT authentication | Stateless API security |
Required: Python 3.11+, Node.js 20+, PostgreSQL 14+
Optional: Docker, Git
git clone <your-repo-url>
cd Backtesting_Engine-maincd backend
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install -r requirements.txtCreate .env file:
DATABASE_URL=postgresql://user:password@localhost:5432/backtesting_db
SECRET_KEY=your-secret-key-generate-with-openssl-rand-hex-32
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
CORS_ORIGINS=http://localhost:3000Start backend:
uvicorn main:app --reload✅ Backend: http://localhost:8000 | 📚 API Docs: http://localhost:8000/docs
cd frontend
npm installCreate .env.local file:
NEXT_PUBLIC_API_URL=http://localhost:8000Start frontend:
npm run dev✅ Frontend: http://localhost:3000
🐳 Docker Setup (Alternative)
# Coming soon - Docker Compose configuration
docker-compose up -d🔧 Detailed Setup Instructions
Option 1: Local PostgreSQL
# macOS
brew install postgresql
brew services start postgresql
createdb backtesting_db
# Ubuntu/Debian
sudo apt install postgresql
sudo systemctl start postgresql
sudo -u postgres createdb backtesting_dbOption 2: Cloud Database
Generate secure SECRET_KEY:
openssl rand -hex 32cd backend
# Tables are auto-created on first run
# Or use Alembic for migrations:
python -m alembic upgrade headPort already in use:
# Backend: Change port
uvicorn main:app --reload --port 8001
# Frontend: Change port in package.json
npm run dev -- -p 3001Database connection error:
- Check PostgreSQL is running:
pg_isready - Verify DATABASE_URL format
- Test connection:
psql $DATABASE_URL
graph LR
A[Register Account] --> B[Connect Broker]
B --> C[Create Strategy]
C --> D[Run Backtest]
D --> E[Analyze Results]
style A fill:#e1f5ff
style C fill:#fff4e1
style D fill:#e8f5e9
style E fill:#fce4ec
Navigate to http://localhost:3000/register and create your account:
- Enter email and password
- Confirm registration
- Login with your credentials
Setup broker API credentials
- Navigate to Settings → Broker Configuration
- Select your broker (e.g., Binance)
- Add API credentials:
- API Key
- API Secret
- Test connection
- Save configuration
Note: This step is optional for testing with demo data
|
|
Example Strategy Code:
from strategies.base import BaseStrategy
class MyStrategy(BaseStrategy):
def __init__(self):
super().__init__()
self.name = "My Custom Strategy"
def should_enter(self, candles):
# Your entry logic here
return True # or False
def should_exit(self, candles, position):
# Your exit logic here
return True # or False📖 Learn More: STRATEGY_FORMAT_GUIDE.md
- Navigate to your saved strategy
- Click "Run Backtest" button
- Configure backtest parameters:
| Parameter | Example | Description |
|---|---|---|
| Symbol | BTC/USDT | Trading pair |
| Timeframe | 1h | Candle interval (1m, 5m, 1h, 1d) |
| Date Range | 2024-01-01 to 2024-12-31 | Historical period |
| Initial Capital | $10,000 | Starting balance |
| Position Size | 10% | Percentage per trade |
- Click "Start Backtest"
- View real-time progress and results
View comprehensive performance analytics:
- 📊 Performance Metrics: Return, Sharpe ratio, max drawdown
- 📈 Equity Curve: Visual portfolio growth
- 📝 Trade Log: Detailed trade-by-trade breakdown
- 💾 Export: Download results as CSV/JSON
- 🔄 Compare: Side-by-side backtest comparison
Backtesting_Engine-main/
├── backend/ # FastAPI backend
│ ├── main.py # Application entry point
│ ├── requirements.txt # Python dependencies
│ ├── api/ # API route handlers
│ │ ├── health.py # Health check endpoints
│ │ ├── brokers.py # Broker-related endpoints
│ │ └── strategies.py # Strategy CRUD endpoints
│ ├── auth/ # Authentication module
│ │ ├── dependencies.py # Auth dependencies
│ │ ├── jwt.py # JWT token handling
│ │ ├── password.py # Password hashing
│ │ ├── routes.py # Auth routes (login/register)
│ │ └── schemas.py # Auth schemas
│ ├── brokers/ # Broker integrations
│ │ ├── base.py # Base broker interface
│ │ ├── binance.py # Binance implementation
│ │ └── factory.py # Broker factory
│ ├── core/ # Core domain models
│ │ └── candle.py # Candle data structure
│ ├── db/ # Database configuration
│ │ └── database.py # SQLAlchemy setup
│ ├── engine/ # Backtesting engine
│ │ ├── backtest.py # Main backtest runner
│ │ └── position.py # Position management
│ ├── models/ # SQLAlchemy models
│ │ ├── user.py # User model
│ │ ├── strategy.py # Strategy model
│ │ └── backtest.py # Backtest model
│ ├── strategies/ # Strategy framework
│ │ ├── base.py # Base strategy class
│ │ ├── indicators.py # Technical indicators
│ │ ├── loader.py # Dynamic strategy loader
│ │ └── schemas.py # Strategy schemas
│ └── examples/ # Example strategies
│ └── strategies/
│ ├── ma_crossover.py
│ ├── rsi_mean_reversion.py
│ └── macd_momentum.py
│
├── frontend/ # Next.js frontend
│ ├── package.json # Node dependencies
│ ├── next.config.ts # Next.js configuration
│ ├── tsconfig.json # TypeScript configuration
│ ├── app/ # Next.js App Router
│ │ ├── layout.tsx # Root layout
│ │ ├── page.tsx # Home page
│ │ ├── (auth)/ # Auth route group
│ │ │ ├── login/ # Login page
│ │ │ └── register/ # Register page
│ │ └── (dashboard)/ # Dashboard route group
│ │ ├── dashboard/ # Main dashboard
│ │ ├── strategies/ # Strategy management
│ │ └── backtests/ # Backtest results
│ ├── components/ # React components
│ │ ├── layout/ # Layout components
│ │ └── ui/ # UI components (buttons, cards, etc.)
│ └── lib/ # Utilities and configs
│ ├── api.ts # API client
│ ├── config.ts # App configuration
│ └── types.ts # TypeScript types
│
├── DEPLOYMENT_GUIDE.md # Comprehensive deployment guide
├── QUICK_DEPLOY.md # Quick deployment (Railway)
├── QUICK_DEPLOY_RENDER.md # Quick deployment (Render)
├── START_HERE.md # Getting started guide
└── README.md # This file
Once the backend is running, access the interactive API documentation:
- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc
POST /auth/register # Register new user
POST /auth/login # Login and get JWT token
GET /auth/me # Get current user info
GET /api/strategies # List all strategies
POST /api/strategies # Create new strategy
GET /api/strategies/{id} # Get strategy by ID
PUT /api/strategies/{id} # Update strategy
DELETE /api/strategies/{id} # Delete strategy
POST /api/strategies/{id}/backtest # Run backtest
GET /api/brokers # List available brokers
POST /api/brokers/connect # Connect broker API
GET /api/brokers/candles # Fetch historical data
GET /health # Health check
GET /health/db # Database health
All protected endpoints require a JWT token in the Authorization header:
Authorization: Bearer <your-jwt-token>
from strategies.base import BaseStrategy
from strategies.indicators import sma, rsi, macd
class MyCustomStrategy(BaseStrategy):
"""
My custom trading strategy description
"""
def __init__(self, param1=20, param2=50):
super().__init__()
self.name = "My Custom Strategy"
self.param1 = param1
self.param2 = param2
def should_enter(self, candles):
"""
Entry logic - return True to open position
Args:
candles: List of Candle objects (OHLCV data)
Returns:
bool: True if entry condition is met
"""
if len(candles) < self.param2:
return False
# Calculate indicators
sma_short = sma(candles, self.param1)
sma_long = sma(candles, self.param2)
# Entry condition: short SMA crosses above long SMA
return sma_short[-1] > sma_long[-1] and sma_short[-2] <= sma_long[-2]
def should_exit(self, candles, position):
"""
Exit logic - return True to close position
Args:
candles: List of Candle objects
position: Current position object
Returns:
bool: True if exit condition is met
"""
if len(candles) < self.param2:
return False
# Calculate indicators
sma_short = sma(candles, self.param1)
sma_long = sma(candles, self.param2)
# Exit condition: short SMA crosses below long SMA
return sma_short[-1] < sma_long[-1] and sma_short[-2] >= sma_long[-2]The platform provides common technical indicators:
- Moving Averages:
sma(),ema() - Momentum:
rsi(),macd(),stochastic() - Volatility:
bollinger_bands(),atr() - Volume:
obv(),volume_sma()
See STRATEGY_FORMAT_GUIDE.md for complete documentation.
-
Vercel + Railway (Recommended - 5 minutes)
-
Vercel + Render (Popular - 10 minutes)
-
Both on Render
Before deploying, review:
Backend:
DATABASE_URL=postgresql://...
SECRET_KEY=...
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
CORS_ORIGINS=https://your-frontend-domain.comFrontend:
NEXT_PUBLIC_API_URL=https://your-backend-api.comcd backend
# Run all tests
pytest
# Run with coverage
pytest --cov=.
# Run specific test file
pytest tests/test_backtest.pycd frontend
# Run tests (if configured)
npm test
# Run linting
npm run lintSee INTEGRATION_TEST.md for end-to-end testing guide.
Import backend/POSTMAN_COLLECTION.json to test API endpoints.
- START_HERE.md - Quick start guide
- DEPLOYMENT_GUIDE.md - Complete deployment guide
- BACKTESTING_EXPLANATION.md - How backtesting works
- STRATEGY_FORMAT_GUIDE.md - Strategy development guide
- STRATEGY_QUICK_REFERENCE.md - Quick reference
- POSTMAN_TESTING_GUIDE.md - API testing guide
- PLATFORM_COMPARISON.md - Deployment platform comparison
- PROJECT_STATUS.md - Current project status
- Core backtesting engine with event-driven architecture
- User authentication and authorization
- Strategy management system
- Binance integration
- Performance analytics dashboard
- Monaco code editor integration
- Paper trading mode (simulated live trading)
- Additional broker integrations (Zerodha, Alpaca)
- Strategy marketplace
- Mobile responsive improvements
- Real-time trading (live execution)
- Portfolio optimization tools
- Machine learning strategy builder
- Social features (strategy sharing, leaderboards)
- Advanced charting with TradingView integration
- Webhook notifications (Discord, Telegram)
- Multi-currency support
- Options & futures strategies
💡 Have a feature request? Open an issue with the enhancement label.
- 🍴 Fork the repository
- 🔀 Create a feature branch
git checkout -b feature/amazing-feature
- ✍️ Make your changes
- ✅ Test your changes
# Backend tests cd backend && pytest # Frontend linting cd frontend && npm run lint
- 💬 Commit with clear messages
git commit -m 'feat: Add amazing feature' - 📤 Push to your fork
git push origin feature/amazing-feature
- 🎯 Open a Pull Request
|
|
# Install pre-commit hooks
pip install pre-commit
pre-commit install
# Run tests
cd backend && pytest --cov
cd frontend && npm test
# Format code
cd backend && black . && isort .
cd frontend && npm run format📖 Read our CONTRIBUTING.md for detailed guidelines.
- START_HERE.md - Getting started guide
- QUICK_DEPLOY.md - Quick deployment
- STRATEGY_FORMAT_GUIDE.md - Strategy development
- POSTMAN_TESTING_GUIDE.md - API testing
- Report bugs via GitHub Issues
- Ask questions in GitHub Discussions
Made with ❤️ for algorithmic traders and quantitative analysts
License: MIT