A professional algorithmic trading system with institutional-grade risk management, machine learning capabilities, and comprehensive backtesting.
Built for paper and live trading via Alpaca Markets API.
- Real-time Trading: Automated execution via Alpaca Markets
- Multiple Strategies: Mean reversion, momentum, ML-based options pricing
- Risk Management: Position sizing, stop-loss, portfolio limits
- Performance Tracking: Complete trade history and P&L analysis
- Kelly Criterion position sizing
- Volatility-adjusted sizing (ATR-based)
- Multiple stop-loss types (percentage, trailing, time-based)
- Portfolio exposure limits and correlation analysis
- Value at Risk (VaR) calculation
- Daily loss and drawdown circuit breakers
- Neural network for options pricing
- Black-Scholes model comparison
- Feature engineering with technical indicators
- Model versioning and experiment tracking
- PostgreSQL database for persistent storage
- Real-time price tracking and historical data
- Performance metrics (Sharpe ratio, win rate, etc.)
- Trade and position management
- Python 3.10+
- PostgreSQL 14+
- Redis 6+ (optional, for advanced features)
- Alpaca Markets account (Sign up here)
- Clone and setup:
git clone https://github.com/KushagraKanaujia/trading-bot.git
cd trading-bot
chmod +x setup.sh
./setup.sh- Configure environment:
cp .env.example .env
# Edit .env with your Alpaca API keys- Initialize database:
# Install PostgreSQL
brew install postgresql@14 # macOS
# or
sudo apt-get install postgresql-14 # Ubuntu
# Create database
createdb trading_bot
# Initialize tables
python -c "from src.models import init_db; init_db()"- Run tests:
pytest tests/ -vfrom src.risk import RiskManager
from src.config import get_settings
# Initialize risk manager
risk_mgr = RiskManager()
# Calculate position size
size = risk_mgr.calculate_position_size(
symbol="AAPL",
price=175.0,
account_value=100000,
volatility=2.5 # ATR
)
# Check if trade is allowed
can_trade, reason = risk_mgr.can_open_position(
symbol="AAPL",
side="buy",
proposed_quantity=size,
price=175.0,
account_value=100000
)
if can_trade:
print(f"Trade approved: {size} shares")
else:
print(f"Trade blocked: {reason}")Edit .env to configure risk parameters:
# Position Sizing
MAX_POSITION_SIZE=0.02 # 2% max per trade
MAX_PORTFOLIO_EXPOSURE=0.5 # 50% max total exposure
# Stop Loss
STOP_LOSS_PERCENTAGE=0.02 # 2% stop-loss
TAKE_PROFIT_PERCENTAGE=0.05 # 5% take-profit
TRAILING_STOP_PERCENTAGE=0.03 # 3% trailing stop
# Loss Limits
DAILY_LOSS_LIMIT=0.05 # Halt if daily loss > 5%
MAX_DRAWDOWN_LIMIT=0.15 # Halt if drawdown > 15%trading-bot/
├── src/
│ ├── config/ # Configuration management
│ ├── models/ # Database models
│ ├── risk/ # Risk management system
│ ├── strategies/ # Trading strategies
│ ├── ml/ # Machine learning models
│ ├── data/ # Data fetching
│ ├── execution/ # Order execution
│ └── backtest/ # Backtesting engine
├── tests/ # Test suite
├── .env.example # Environment template
└── setup.sh # Automated setup
Run the test suite:
# All tests
pytest
# With coverage
pytest --cov=src --cov-report=html
# Specific module
pytest tests/test_risk_manager.py -vStores all executed trades with P&L tracking.
Current holdings with unrealized P&L.
Time-series OHLCV data for all tracked symbols.
Daily performance statistics and risk metrics.
The system implements multiple layers of risk control:
-
Pre-Trade Checks
- Position size limits
- Portfolio exposure limits
- Correlation checks
- Daily loss limits
-
Position Sizing
- Kelly Criterion (optimal)
- Fixed percentage
- Volatility-adjusted
-
Exit Management
- Stop-loss orders
- Trailing stops
- Take-profit targets
- Time-based exits
-
Portfolio Monitoring
- Value at Risk (VaR)
- Portfolio beta
- Maximum drawdown tracking
The system tracks:
- Total P&L (realized and unrealized)
- Sharpe ratio, Sortino ratio, Calmar ratio
- Win rate and profit factor
- Maximum drawdown
- Daily/monthly returns
- Risk-adjusted returns
# Activate virtual environment
source venv/bin/activate
# Start development server
python -m src.api.main
# Run in background
nohup python -m src.api.main > logs/app.log 2>&1 &Create a new strategy class in src/strategies/:
from src.strategies.base import BaseStrategy
class MyStrategy(BaseStrategy):
def generate_signals(self, data):
# Your strategy logic here
pass# Check PostgreSQL status
pg_isready
# Test connection
psql trading_bot -c "SELECT 1;"# Add to PYTHONPATH
export PYTHONPATH="${PYTHONPATH}:$(pwd)"# Check Redis
redis-cli ping # Should return PONG
# Start Redis
redis-serverSee docs/DEPLOYMENT.md for production deployment instructions.
For Heroku deployment:
heroku create
heroku addons:create heroku-postgresql:standard-0
git push heroku main- Fork the repository
- Create a feature branch
- Make your changes
- Run tests:
pytest - Submit a pull request
MIT License - see LICENSE file for details
Note: Start with paper trading and test for at least 3 months before considering live trading.
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create a feature branch
- Make your changes
- Run tests:
pytest - Submit a pull request
- Follow PEP 8 style guide
- Add tests for new features
- Update documentation as needed
- Use type hints