A full-stack trading platform with real-time market data, order matching, portfolio management, risk controls, and backtesting capabilities.
Features β’ Quick Start β’ Documentation β’ API β’ Testing
- Overview
- Features
- Architecture
- Technology Stack
- Quick Start
- Installation
- Configuration
- Usage
- API Documentation
- Testing
- Project Structure
- Contributing
- License
The Trading Engine is a comprehensive, production-ready trading platform that combines a powerful Django backend with a modern React frontend. It provides institutional-grade features including real-time market data integration, advanced order matching, portfolio tracking, risk management, and strategy backtesting.
β Real-time Market Data - Integration with Alpaca Markets API for live market data β Order Matching Engine - Custom LIMIT, MARKET, and STOP_LOSS order processing β Portfolio Management - Real-time P&L tracking, position management, and performance analytics β Risk Management - Multi-level risk controls with configurable limits β Backtesting Engine - Strategy validation with comprehensive performance metrics β JWT Authentication - Secure token-based authentication with automatic refresh β RESTful API - Complete REST API with Swagger/OpenAPI documentation β Modern UI - Clean, responsive React interface with Material-UI β Comprehensive Testing - 66+ tests with 100% feature coverage
- Alpaca Markets Integration - Live market data from Alpaca's trading API
- Multi-Asset Support - Trade stocks, ETFs, and other supported securities
- Bid/Ask Spreads - Real-time order book data with best bid/ask prices
- Price Updates - Automatic price refreshes (10-second intervals)
- Historical Data - Access to historical bars for backtesting
- Order Types:
LIMIT- Execute at specified price or betterMARKET- Execute at best available priceSTOP_LOSS- Trigger sell when price falls below threshold
- Price-Time Priority - FIFO matching algorithm
- Partial Fills - Support for partial order execution
- Order Status Tracking - PENDING, FILLED, CANCELLED, REJECTED
- Real-time Matching - Sub-second order processing
- Trade Recording - Complete audit trail of all executions
- Real-time Valuation - Live portfolio value updates
- Position Tracking:
- Current positions with quantity and average cost
- Unrealized P&L (mark-to-market)
- Cost basis calculations
- Position-level performance metrics
- Cash Management:
- Cash balance tracking
- Buying power calculations
- Margin utilization (if enabled)
- Performance Analytics:
- Total return ($ and %)
- Daily/weekly/monthly P&L
- Win rate and trade statistics
- Multi-Asset Portfolios - Support for diversified holdings
- Order-Level Controls:
- Maximum order size limits
- Minimum price validation
- Size validation (must be positive)
- Portfolio-Level Controls:
- Maximum position size limits
- Buying power validation
- Leverage limits
- Trading Controls:
- Daily trade limit enforcement
- Maximum open orders limit
- Daily loss limits
- Audit Logging:
- All risk violations logged
- IP address tracking
- Timestamp recording
- 11 event types tracked
- Configurable Limits - Per-user risk parameter customization
- Strategy Development:
- Python-based strategy coding
- Custom strategy framework
- Simple MA crossover (built-in example)
- Historical Testing:
- Date range selection
- Historical bar data access
- Multi-symbol support
- Performance Metrics:
- Total return ($ and %)
- Sharpe ratio
- Maximum drawdown
- Win rate and profit factor
- Average win/loss
- Total trades executed
- Equity Curve - Daily portfolio value tracking
- Trade History - All backtest trades recorded
- JWT Authentication - Industry-standard token-based auth
- Token Management:
- Access tokens (60-minute lifetime)
- Refresh tokens (7-day lifetime)
- Automatic token refresh
- Token blacklist on rotation
- Secure Sessions - HTTP-only cookies, CSRF protection
- User Isolation - Strict data access controls
- Password Security - Django's password hashing
- Login/Logout - Secure authentication flow
- Portfolio Dashboard:
- Total value, cash balance, buying power
- P&L summary with percentage changes
- Positions table with unrealized P&L
- Recent trades history
- Markets Page:
- Grid view of all tradable assets
- Live price updates with change indicators
- Integrated order placement dialog
- Bid/ask display
- Orders Management:
- Complete order history
- Status tracking and filtering
- Cancel pending orders
- Real-time updates
- Backtesting Interface:
- Backtest creation form
- Results visualization
- Performance metrics display
- Backtest history
- Responsive Design - Works on desktop, tablet, and mobile
- Real-time Updates - Auto-refresh for live data
- RESTful API - Complete REST endpoints
- Swagger/OpenAPI - Interactive API documentation at
/swagger/ - Pagination - Efficient data retrieval (50 items per page)
- Filtering & Search - Query parameters for data filtering
- Rate Limiting - Throttling to prevent abuse
- CORS Support - Cross-origin requests enabled
- Django Admin - Full admin panel at
/admin/ - Model Management - CRUD for all models
- User Management - User and permission administration
- Data Export - CSV export capabilities
- Custom Admin Views - Enhanced admin for complex models
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Client Layer β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β React Frontend (Port 3000) β β
β β - Material-UI Components β β
β β - JWT Authentication β β
β β - Real-time Updates β β
β β - Responsive Design β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
β HTTP/REST API
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Application Layer β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Django Backend (Port 8000) β β
β β ββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β β β Django REST Framework β β β
β β β - JWT Authentication Middleware β β β
β β β - API ViewSets & Serializers β β β
β β β - Permission Classes β β β
β β β - Rate Limiting β β β
β β ββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Business Logic Layer β
β βββββββββββββββββββ¬ββββββββββββββββββ¬βββββββββββββββββββ β
β β Matching Engineβ Risk Management β Backtest Engine β β
β β - Order Queue β - Validators β - Strategy Exec β β
β β - Price Match β - Limit Check β - Metrics Calc β β
β β - Trade Exec β - Audit Logger β - Performance β β
β βββββββββββββββββββ΄ββββββββββββββββββ΄βββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Data Layer β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Database (SQLite/PostgreSQL) β β
β β - Asset, Order, Trade β β
β β - Portfolio, Position β β
β β - RiskLimit, AuditLog β β
β β - BacktestRun, BacktestResult β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β External Services β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Alpaca Markets API β β
β β - Real-time Market Data β β
β β - Historical Bars β β
β β - Market Snapshots β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
User (Django Auth)
βββΊ Portfolio
βββΊ Position (many)
βββΊ RiskLimit
Order
βββΊ Asset
βββΊ Trade (via matching)
Trade
βββΊ buy_order (Order)
βββΊ sell_order (Order)
βββΊ buyer (User)
βββΊ seller (User)
BacktestRun
βββΊ User
βββΊ BacktestResult (one-to-one)
AuditLog
βββΊ User
- Django 4.2.10 - Web framework
- Django REST Framework 3.14 - REST API framework
- djangorestframework-simplejwt 5.3.1 - JWT authentication
- drf-yasg 1.21.7 - Swagger/OpenAPI documentation
- django-cors-headers 4.3.0 - CORS middleware
- django-ratelimit 4.1.0 - Rate limiting
- alpaca-trade-api 3.0.2 - Market data integration
- pandas 2.1.4 - Data analysis for backtesting
- numpy 1.26.3 - Numerical computations
- sortedcontainers 2.4.0 - Order book data structures
- redis 5.0.1 - Caching (optional)
- PostgreSQL or SQLite - Database
- React 18.2 - UI framework
- TypeScript 4.9 - Type-safe JavaScript
- Material-UI 5.16 - Component library
- React Router 6.28 - Client-side routing
- Fetch API - HTTP client
- Django Test Framework - Backend testing
- unittest.mock - Mocking for tests
- WhiteNoise 6.6 - Static file serving
- Gunicorn 21.2 - WSGI server (production)
- Python 3.9 or higher
- Node.js 16 or higher
- npm or yarn
- Git
# Clone the repository
git clone https://github.com/Odion-Sonny/order_book
cd order_book
# Run the quick start script
chmod +x start_trading_platform.sh
./start_trading_platform.shThis will:
- Start Django backend on http://localhost:8000
- Start React frontend on http://localhost:3000
- Open your browser automatically
- Frontend: http://localhost:3000
- Backend API: http://localhost:8000
- API Docs: http://localhost:8000/swagger/
- Admin Panel: http://localhost:8000/admin/
Username: testuser
Password: testpass123
-
Navigate to backend directory:
cd trading_engine -
Create virtual environment (recommended):
python3 -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies:
pip install -r requirements.txt
-
Configure environment variables: Create a
.envfile intrading_engine/:DJANGO_SECRET_KEY=your-secret-key-here DJANGO_DEBUG=True DJANGO_ALLOWED_HOSTS=localhost,127.0.0.1 # Alpaca API (optional but recommended) ALPACA_API_KEY=your-alpaca-api-key ALPACA_SECRET_KEY=your-alpaca-secret-key ALPACA_BASE_URL=https://paper-api.alpaca.markets # Database (optional, defaults to SQLite) DATABASE_URL=sqlite:///db.sqlite3
-
Run migrations:
python3 manage.py migrate
-
Create superuser:
python3 manage.py createsuperuser
-
Create test user (for frontend):
python3 manage.py shell
from django.contrib.auth.models import User User.objects.create_user('testuser', '[email protected]', 'testpass123') exit()
-
Start the server:
python3 manage.py runserver
-
Navigate to frontend directory:
cd frontend -
Install dependencies:
npm install
-
Start development server:
npm start
The frontend will open at http://localhost:3000
| Variable | Description | Default |
|---|---|---|
DJANGO_SECRET_KEY |
Django secret key | Required |
DJANGO_DEBUG |
Debug mode | False |
DJANGO_ALLOWED_HOSTS |
Allowed hosts | localhost,127.0.0.1 |
ALPACA_API_KEY |
Alpaca API key | Empty |
ALPACA_SECRET_KEY |
Alpaca secret key | Empty |
ALPACA_BASE_URL |
Alpaca API base URL | Paper trading URL |
DATABASE_URL |
Database connection | SQLite |
- Sign up at Alpaca Markets
- Get API keys from dashboard
- Add keys to
.envfile - Restart backend server
SQLite (Default - Development):
# No configuration needed
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}PostgreSQL (Production):
DATABASE_URL=postgresql://user:password@localhost:5432/trading_dbThe frontend API base URL is configured in src/services/api.ts:
const API_BASE_URL = 'http://localhost:8000';For production, update this to your production API URL.
- Navigate to http://localhost:3000
- Enter credentials
- Click "Sign In"
- Dashboard shows total value, cash, buying power, P&L
- Positions table displays all holdings
- Recent trades section shows last 10 trades
- Data refreshes every 30 seconds
- Click "Markets" in sidebar
- Browse available assets
- Click "Trade" on desired asset
- Fill order form:
- Select BUY or SELL
- Choose order type (LIMIT/MARKET/STOP_LOSS)
- Enter quantity
- Enter price (for limit orders)
- Click "Place Order"
- Click "Orders" in sidebar
- View all orders with status
- Cancel pending orders (delete icon)
- Refresh to see updates
- Click "Backtesting" in sidebar
- Fill in backtest form:
- Name your backtest
- Select date range
- Set initial capital
- Enter strategy code
- Click "Run Backtest"
- View results in history panel
# Get tokens
curl -X POST http://localhost:8000/api/auth/token/ \
-H "Content-Type: application/json" \
-d '{"username": "testuser", "password": "testpass123"}'
# Response:
# {
# "access": "eyJ0eXAiOiJKV1QiLCJhbGc...",
# "refresh": "eyJ0eXAiOiJKV1QiLCJhbGc..."
# }
# Use access token in requests
curl http://localhost:8000/api/portfolios/current/ \
-H "Authorization: Bearer <access-token>"curl -X POST http://localhost:8000/api/orders/ \
-H "Authorization: Bearer <access-token>" \
-H "Content-Type: application/json" \
-d '{
"asset": 1,
"side": "BUY",
"order_type": "LIMIT",
"price": "150.00",
"size": "10.00"
}'curl http://localhost:8000/api/assets/market_data/ \
-H "Authorization: Bearer <access-token>"Access the Swagger UI at: http://localhost:8000/swagger/
POST /api/auth/token/- Login (get tokens)POST /api/auth/token/refresh/- Refresh access tokenPOST /api/auth/token/verify/- Verify token
GET /api/assets/- List all assetsGET /api/assets/{id}/- Get asset detailsGET /api/assets/market_data/- Get real-time market data
GET /api/orders/- List user's ordersPOST /api/orders/- Place new orderGET /api/orders/{id}/- Get order detailsPOST /api/orders/{id}/cancel/- Cancel order
GET /api/portfolios/- List portfoliosGET /api/portfolios/current/- Get current user's portfolioGET /api/portfolios/performance/- Get performance metrics
GET /api/positions/- List user's positionsGET /api/positions/{id}/- Get position details
GET /api/trades/- List tradesGET /api/trades-list/- Get formatted trade history
GET /api/backtests/- List backtestsPOST /api/backtests/- Create backtestGET /api/backtests/{id}/- Get backtest detailsPOST /api/backtests/{id}/run/- Run backtest
GET /api/risk-limits/- List risk limitsPATCH /api/risk-limits/{id}/- Update risk limits
GET /api/audit-logs/- View audit trail
All API responses follow this format:
Success:
{
"count": 10,
"next": "http://localhost:8000/api/orders/?page=2",
"previous": null,
"results": [...]
}Error:
{
"detail": "Error message here"
}cd trading_engine
python3 manage.py test order_book.tests order_book.tests_comprehensive --verbosity=2Total Tests: 66
- Original test suite: 23 tests
- Comprehensive test suite: 43 tests
- Success rate: 100%
- Asset Tests (2) - Model creation, uniqueness
- Order Tests (3) - Creation, status transitions, market orders
- OrderBook Tests (2) - Creation, uniqueness
- Matching Engine Tests (2) - Limit orders, price priority
- API Tests (4) - Endpoints, pagination, authentication
- Authentication Tests (2) - User creation, login
- Real-time Data Tests (2) - Price updates, market data API
- Risk Management Tests (3) - Validation, limits
- Integration Tests (1) - End-to-end flow
- Portfolio Management (5) - Valuation, P&L, buying power
- Position Tracking (5) - Cost basis, unrealized P&L, updates
- Risk Management (8) - All validators, limits, enforcement
- Trade Recording (3) - Execution, history, ordering
- Audit Logging (4) - Event types, ordering, tracking
- Backtesting (3) - Execution, results, metrics
- JWT Authentication (5) - Token lifecycle, refresh, verification
- API Integration (10) - All ViewSets, permissions, errors
# Portfolio tests only
python3 manage.py test order_book.tests_comprehensive.PortfolioManagementTests
# Risk management tests only
python3 manage.py test order_book.tests_comprehensive.RiskManagementTests
# API integration tests only
python3 manage.py test order_book.tests_comprehensive.APIIntegrationTestsorder_book/
βββ trading_engine/ # Django backend
β βββ trading_engine/ # Project settings
β β βββ settings.py # Configuration
β β βββ urls.py # URL routing
β β βββ wsgi.py # WSGI entry point
β βββ order_book/ # Main app
β β βββ models.py # Data models
β β βββ serializers.py # DRF serializers
β β βββ views.py # API views
β β βββ views_extended.py # Extended ViewSets
β β βββ admin.py # Admin configuration
β β βββ tests.py # Original tests
β β βββ tests_comprehensive.py # Comprehensive tests
β β βββ services/ # Business logic
β β βββ matching_engine.py # Order matching
β β βββ risk_management.py # Risk controls
β β βββ backtesting_engine.py # Backtesting
β β βββ audit_logger.py # Audit logging
β β βββ alpaca_service.py # Market data
β βββ manage.py # Django CLI
β βββ requirements.txt # Python dependencies
βββ frontend/ # React frontend
β βββ src/
β β βββ services/ # API layer
β β β βββ api.ts # API service
β β βββ contexts/ # State management
β β β βββ AuthContext.tsx # Auth context
β β βββ pages/ # Page components
β β β βββ Login.tsx # Login page
β β β βββ Portfolio.tsx # Portfolio dashboard
β β β βββ Markets.tsx # Markets & trading
β β β βββ Orders.tsx # Order management
β β β βββ Backtesting.tsx # Backtesting UI
β β βββ components/ # Reusable components
β β β βββ AppLayout.tsx # Main layout
β β βββ App.tsx # Main app
β βββ package.json # Node dependencies
β βββ tsconfig.json # TypeScript config
βββ README.md # This file
βββ FRONTEND_SETUP_GUIDE.md # Frontend guide
βββ FRONTEND_OVERHAUL_SUMMARY.md # Implementation details
βββ TESTING_SUMMARY.md # Testing documentation
βββ IMPLEMENTATION_COMPLETE.md # Feature documentation
βββ start_trading_platform.sh # Quick start script
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch
git checkout -b feature/your-feature-name
- Make your changes
- Run tests
python3 manage.py test - Commit your changes
git commit -m "Add: your feature description" - Push to your fork
git push origin feature/your-feature-name
- Create a Pull Request
- Follow PEP 8 for Python code
- Use TypeScript for frontend code
- Write tests for new features
- Update documentation
- Maintain backwards compatibility
This project is licensed under the MIT License - see the LICENSE file for details.
Important Notice:
This trading platform is provided for educational and experimental purposes only. Trading in financial markets involves significant risk and may not be suitable for everyone.
Key Points:
- Not Financial Advice: This software does not constitute financial, investment, or trading advice
- Use at Your Own Risk: You are solely responsible for any trading decisions and their outcomes
- Paper Trading Recommended: Start with paper trading (simulated) before using real money
- No Guarantees: Past performance does not guarantee future results
- Regulatory Compliance: Ensure compliance with local laws and regulations
- Professional Consultation: Consult with financial professionals before making investment decisions
Liability: The developers and contributors of this project are not liable for any financial losses, damages, or consequences resulting from the use of this software.
- API Docs: http://localhost:8000/swagger/
Backend won't start:
- Check Python version (3.9+)
- Verify all dependencies installed
- Check
.envfile exists - Review error logs
Frontend won't start:
- Check Node.js version (16+)
- Run
npm install - Clear npm cache:
npm cache clean --force - Delete
node_modulesand reinstall
Database errors:
- Run migrations:
python3 manage.py migrate - Check database permissions
- Verify DATABASE_URL in
.env
Authentication errors:
- Verify user exists
- Check JWT token not expired
- Ensure CORS configured correctly
- WebSocket support for real-time updates
- Advanced charting with TradingView integration
- Options trading support
- Multi-currency support
- Mobile app (React Native)
- Advanced analytics dashboard
- Machine learning strategy builder
- Social trading features
- Redis caching layer
- Database query optimization
- API response compression
- CDN integration for static assets
- Docker containerization
- Kubernetes deployment configs
- CI/CD pipeline (GitHub Actions)
- Automated deployment scripts
- Monitoring and alerting
Made with β€οΈ using Django & React