Quick Start Guide¶
Get up and running with DSTA (Dr. Strange Trading Analysis) in under 10 minutes!
What is DSTA?¶
DSTA is a professional-grade algorithmic trading system for cryptocurrency markets. It provides:
- Backtesting Engine: Test trading strategies on historical data
- Live Trading Bot: Execute strategies in real-time
- Technical Indicators: 100+ indicators via TA-Lib integration
- Data Management: Automated collection and storage of market data
- Risk Management: Position sizing, stop-loss, and risk limits
- Performance Analytics: Comprehensive metrics and reporting
Prerequisites¶
Before you begin, ensure you have:
- Python 3.12+ installed
- Docker & Docker Compose for services
- 10GB free disk space
- 8GB RAM (16GB recommended)
- Git for cloning the repository
Installation¶
1. Clone the Repository¶
2. Set Up Python Environment¶
# Install uv (recommended, faster than pip)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Create virtual environment
uv venv
source .venv/bin/activate # Linux/macOS
# or
.venv\Scripts\activate # Windows
3. Install Dependencies¶
4. Start Services¶
# Start PostgreSQL and Redis
cd deploy
docker-compose up -d
# Verify services are running
docker-compose ps
5. Initialize Database¶
# Run initialization script
cd ..
./scripts/init_db.sh --with-sample-data
# Or manually
cd src
python manage.py migrate
python manage.py createsuperuser # username: admin, password: admin
6. Verify Installation¶
cd src
# Start Django server
python manage.py runserver
# In another terminal, test the API
curl http://localhost:8000/api/health/
# Should return: {"status": "ok"}
🎉 Congratulations! Your DSTA installation is complete.
Your First Backtest¶
Let's run a simple moving average crossover strategy.
1. Create a Strategy File¶
Create my_first_strategy.py:
"""
Simple Moving Average Crossover Strategy
Buy when fast MA crosses above slow MA, sell when it crosses below.
"""
import sys
sys.path.insert(0, 'src')
from backtesting import Backtest
from backtesting.strategy import BaseStrategy
from backtesting.indicators import sma
import numpy as np
class SMACrossover(BaseStrategy):
"""
Simple Moving Average Crossover Strategy.
Parameters:
fast_period: Fast MA period (default: 10)
slow_period: Slow MA period (default: 30)
"""
# Strategy parameters
fast_period = 10
slow_period = 30
def init(self):
"""Initialize indicators."""
# Calculate moving averages on close prices
close = np.array([c['close'] for c in self.data])
self.fast_ma = sma(close, self.fast_period)
self.slow_ma = sma(close, self.slow_period)
def next(self):
"""Execute on each new candle."""
# Need enough data for both MAs
if len(self.data) < self.slow_period:
return
# Get current and previous MA values
current_fast = self.fast_ma
current_slow = self.slow_ma
# Crossover logic
if current_fast > current_slow:
# Golden cross - buy signal
if not self.position:
self.buy()
elif current_fast < current_slow:
# Death cross - sell signal
if self.position:
self.sell()
if __name__ == '__main__':
# Create backtest with sample data
bt = Backtest(
strategy=SMACrossover,
cash=10000, # Starting capital
commission=0.001 # 0.1% commission
)
# Load sample data (will be replaced with real data later)
# For now, create synthetic data
from datetime import datetime, timedelta
import random
# Generate 180 days of hourly data
data = []
base_price = 50000
start_time = datetime.now() - timedelta(days=180)
for i in range(180 * 24): # 180 days * 24 hours
price_change = random.uniform(-0.01, 0.01)
base_price *= (1 + price_change)
data.append({
'timestamp': start_time + timedelta(hours=i),
'open': base_price * (1 + random.uniform(-0.002, 0.002)),
'high': base_price * (1 + random.uniform(0, 0.005)),
'low': base_price * (1 - random.uniform(0, 0.005)),
'close': base_price,
'volume': random.uniform(100, 1000)
})
# Run backtest
print("Running backtest...")
stats = bt.run(data)
# Print results
print("\n" + "="*60)
print("BACKTEST RESULTS")
print("="*60)
print(f"Total Return: {stats['total_return']:.2%}")
print(f"Sharpe Ratio: {stats['sharpe_ratio']:.2f}")
print(f"Max Drawdown: {stats['max_drawdown']:.2%}")
print(f"Win Rate: {stats['win_rate']:.2%}")
print(f"Total Trades: {stats['num_trades']}")
print("="*60)
2. Run the Backtest¶
You should see output like:
Running backtest...
============================================================
BACKTEST RESULTS
============================================================
Total Return: 15.32%
Sharpe Ratio: 1.25
Max Drawdown: -8.45%
Win Rate: 55.00%
Total Trades: 42
============================================================
Using Real Market Data¶
1. Configure Exchange API¶
Create .env_files/dev.env:
# Binance API (read-only for data collection)
BINANCE_API_KEY=your_api_key_here
BINANCE_API_SECRET=your_api_secret_here
# Database
DATABASE_URL=postgresql://dsta:dsta@localhost:5432/dsta_dev
2. Collect Historical Data¶
from api.tasks.data_collection import collect_candlesticks
from datetime import datetime, timedelta
# Collect data
end_time = datetime.now()
start_time = end_time - timedelta(days=30)
collect_candlesticks(
exchange='binance',
symbol='BTCUSDT',
interval='1h',
start_time=start_time,
end_time=end_time
)
print("Data collection complete!")
3. Run Backtest with Real Data¶
from api.models import Candlestick
from backtesting import Backtest
from my_first_strategy import SMACrossover
# Load data from database
candles = Candlestick.objects.filter(
exchange='binance',
symbol='BTCUSDT',
interval='1h'
).order_by('timestamp').values(
'timestamp', 'open_price', 'high_price',
'low_price', 'close_price', 'volume'
)
# Convert to backtest format
data = [{
'timestamp': c['timestamp'],
'open': float(c['open_price']),
'high': float(c['high_price']),
'low': float(c['low_price']),
'close': float(c['close_price']),
'volume': float(c['volume'])
} for c in candles]
# Run backtest
bt = Backtest(strategy=SMACrossover, cash=10000)
stats = bt.run(data)
print(f"Total Return: {stats['total_return']:.2%}")
Exploring the Admin Interface¶
1. Access Admin Panel¶
Open browser: http://localhost:8000/admin/
Login with credentials created during setup (default: admin/admin)
2. View Market Data¶
In the admin panel: - Candlesticks: View OHLCV data - Trades: Individual trade records - Order Books: Order book snapshots - Market Metrics: BTC dominance, Fear & Greed, etc.
3. Add Sample Data¶
In the admin panel, you can manually add test data or use the Django shell:
Next Steps¶
Now that you're up and running, here's what to explore next:
1. Learn Strategy Development¶
Read the Strategy Development Guide to: - Understand the strategy interface - Learn about available indicators - Implement complex strategies - Optimize parameters
2. Understand Backtesting¶
Check the Backtesting Guide for: - Avoiding common pitfalls - Interpreting results correctly - Walk-forward optimization - Monte Carlo analysis
3. Set Up Live Trading¶
See the Trading Bot Setup Guide to: - Configure the trading bot - Set up risk management - Enable notifications - Monitor performance
4. Explore Technical Indicators¶
Review the TA-Lib Integration Guide to: - Use 150+ technical indicators - Create custom indicators - Optimize indicator performance
Common Tasks¶
Update Market Data¶
# Using Django shell
python manage.py shell
from api.tasks.data_collection import collect_latest_data
collect_latest_data(['BTCUSDT', 'ETHUSDT'])
Run Tests¶
# Run all tests
pytest
# Run specific module tests
pytest tests/backtesting/
# With coverage
pytest --cov=src --cov-report=html
View Logs¶
# Application logs
tail -f logs/app.log
# Docker logs
docker-compose logs -f
# Database logs
docker-compose logs postgres
Stop Services¶
Troubleshooting¶
"Database connection refused"¶
# Check if PostgreSQL is running
docker-compose ps
# Start if not running
docker-compose up -d postgres
# Check logs
docker-compose logs postgres
"Module not found"¶
# Ensure virtual environment is activated
source .venv/bin/activate
# Reinstall dependencies
uv pip install -e .
"Port 8000 already in use"¶
# Find process using port
lsof -i :8000
# Kill process
kill -9 <PID>
# Or use different port
python manage.py runserver 8001
"Migration conflicts"¶
# Show migration status
python manage.py showmigrations
# Merge conflicts
python manage.py makemigrations --merge
Getting Help¶
Need assistance? Here's where to get help:
- Documentation: Check the
docs/directory - GitHub Issues: Report bugs or request features
- Discussions: Ask questions on GitHub Discussions
- Contributing: See CONTRIBUTING.md
Learn More¶
- Development Environment Guide: Detailed setup for contributors
- Architecture Overview: System design and components
- API Documentation: REST API reference
- Database Schema: Database structure and management
Quick Reference¶
Essential Commands¶
# Start services
docker-compose up -d
# Initialize database
./scripts/init_db.sh
# Run server
python manage.py runserver
# Run backtest
python my_strategy.py
# Generate test data
python manage.py generate_test_data --days 30
# Run tests
pytest
# Stop services
docker-compose down
Directory Structure¶
dsta/
├── src/ # Source code
│ ├── api/ # Django app (models, views)
│ ├── backtesting/ # Backtesting engine
│ ├── dsta/ # Django project settings
│ └── manage.py # Django management
├── tests/ # Test files
├── docs/ # Documentation
├── scripts/ # Utility scripts
├── deploy/ # Docker configs
└── data/ # Data storage
Happy trading! 🚀📈