- Creada estructura de carpetas src/backtest/ y src/strategies/ - Añadidos archivos vacíos para backtesting engine - Actualizado README.md con gestión de PostgreSQL: * Comandos start/stop/restart/status * Habilitar/deshabilitar inicio automático * Sección completa de gestión del servicio - Preparado para implementar motor de backtesting
653 lines
14 KiB
Markdown
653 lines
14 KiB
Markdown
# 🤖 Trading Bot - Proyecto Completo
|
|
|
|
Bot de trading algorítmico desarrollado desde cero con Python, PostgreSQL y Machine Learning.
|
|
|
|
## 📋 Tabla de Contenidos
|
|
|
|
- [Estado del Proyecto](#-estado-del-proyecto)
|
|
- [Requisitos](#-requisitos)
|
|
- [Instalación](#-instalación)
|
|
- [Configuración](#-configuración)
|
|
- [Uso](#-uso)
|
|
- [Estructura del Proyecto](#-estructura-del-proyecto)
|
|
- [Base de Datos](#-base-de-datos)
|
|
- [Scripts Disponibles](#-scripts-disponibles)
|
|
- [Testing](#-testing)
|
|
- [Roadmap](#-roadmap)
|
|
- [Troubleshooting](#-troubleshooting)
|
|
|
|
## 🎯 Estado del Proyecto
|
|
|
|
### ✅ Completado (Semanas 1-2)
|
|
|
|
- ✅ Sistema de logging robusto con rotación de archivos
|
|
- ✅ Conexión a exchanges vía CCXT (Binance por defecto)
|
|
- ✅ Descarga de datos históricos con reintentos automáticos
|
|
- ✅ Descarga incremental (continuar desde último timestamp)
|
|
- ✅ Procesamiento y limpieza de datos
|
|
- ✅ Detección de gaps y outliers
|
|
- ✅ Resampleo de timeframes (1h → 4h, 1d, etc.)
|
|
- ✅ Cálculo de retornos (simples y logarítmicos)
|
|
- ✅ Almacenamiento en PostgreSQL con índices optimizados
|
|
- ✅ Sistema anti-duplicados con constraints únicos
|
|
- ✅ Caché con Redis (opcional)
|
|
- ✅ Script de descarga masiva para múltiples símbolos
|
|
- ✅ Tests unitarios
|
|
- ✅ Manejo de errores y reintentos
|
|
|
|
**Datos descargados actualmente:**
|
|
- 5 criptomonedas (BTC, ETH, BNB, SOL, XRP)
|
|
- 3 timeframes (1h, 4h, 1d)
|
|
- 120 días de histórico
|
|
- ~54,000 registros totales
|
|
|
|
### 🔄 En Progreso
|
|
|
|
- ⏳ Backtesting Engine (Semanas 3-4)
|
|
- ⏳ Estrategias de trading (Semanas 5-8)
|
|
- ⏳ Machine Learning (Semanas 5-8)
|
|
|
|
### 📅 Planificado
|
|
|
|
- 📋 Live trading con paper trading
|
|
- 📋 Gestión de riesgo avanzada
|
|
- 📋 Optimización de estrategias
|
|
- 📋 Dashboard web
|
|
- 📋 Alertas y notificaciones
|
|
|
|
## 🔧 Requisitos
|
|
|
|
### Software
|
|
- **Python 3.10+** (probado con 3.12.3)
|
|
- **PostgreSQL 13+**
|
|
- **Redis 6+** (opcional, para caché)
|
|
- Git
|
|
|
|
### Hardware Recomendado
|
|
- 8GB RAM (mínimo)
|
|
- 20GB espacio en disco
|
|
- Para ML: GPU recomendada (futuro)
|
|
|
|
## 📦 Instalación
|
|
|
|
### 1. Clonar el repositorio
|
|
|
|
```bash
|
|
git clone <tu-repositorio>
|
|
cd trading-bot
|
|
```
|
|
|
|
### 2. Crear entorno virtual
|
|
|
|
```bash
|
|
python3 -m venv venv
|
|
|
|
# Linux/Mac:
|
|
source venv/bin/activate
|
|
|
|
# Windows:
|
|
venv\Scripts\activate
|
|
```
|
|
|
|
### 3. Instalar dependencias
|
|
|
|
```bash
|
|
pip install --upgrade pip
|
|
pip install -r requirements.txt
|
|
```
|
|
|
|
### 4. Instalar PostgreSQL
|
|
|
|
**Ubuntu/Debian:**
|
|
```bash
|
|
sudo apt update
|
|
sudo apt install postgresql postgresql-contrib
|
|
sudo systemctl start postgresql
|
|
sudo systemctl enable postgresql
|
|
```
|
|
|
|
**macOS (con Homebrew):**
|
|
```bash
|
|
brew install postgresql@16
|
|
brew services start postgresql@16
|
|
```
|
|
|
|
**Windows:**
|
|
Descargar instalador desde [postgresql.org](https://www.postgresql.org/download/windows/)
|
|
|
|
### 5. Configurar base de datos
|
|
|
|
```bash
|
|
# Conectar a PostgreSQL
|
|
sudo -u postgres psql
|
|
|
|
# Crear base de datos y usuario
|
|
CREATE DATABASE trading_bot;
|
|
CREATE USER trading_user WITH PASSWORD 'tu_password_seguro';
|
|
GRANT ALL PRIVILEGES ON DATABASE trading_bot TO trading_user;
|
|
|
|
# Conectar a la base de datos
|
|
\c trading_bot
|
|
|
|
# Dar permisos sobre el schema
|
|
GRANT ALL ON SCHEMA public TO trading_user;
|
|
|
|
# Salir
|
|
\q
|
|
```
|
|
|
|
### 6. Gestión del servicio PostgreSQL
|
|
|
|
**Iniciar PostgreSQL:**
|
|
```bash
|
|
sudo systemctl start postgresql
|
|
```
|
|
|
|
**Verificar estado:**
|
|
```bash
|
|
sudo systemctl status postgresql
|
|
```
|
|
|
|
**Detener PostgreSQL:**
|
|
```bash
|
|
sudo systemctl stop postgresql
|
|
```
|
|
|
|
**Reiniciar PostgreSQL:**
|
|
```bash
|
|
sudo systemctl restart postgresql
|
|
```
|
|
|
|
**Habilitar inicio automático al arrancar el sistema:**
|
|
```bash
|
|
sudo systemctl enable postgresql
|
|
```
|
|
|
|
**Deshabilitar inicio automático:**
|
|
```bash
|
|
sudo systemctl disable postgresql
|
|
```
|
|
|
|
**Ver si está habilitado el inicio automático:**
|
|
```bash
|
|
systemctl is-enabled postgresql
|
|
```
|
|
|
|
### 6. Instalar Redis (opcional pero recomendado)
|
|
|
|
**Ubuntu/Debian:**
|
|
```bash
|
|
sudo apt install redis-server
|
|
sudo systemctl start redis
|
|
```
|
|
|
|
**macOS:**
|
|
```bash
|
|
brew install redis
|
|
brew services start redis
|
|
```
|
|
|
|
## ⚙️ Configuración
|
|
|
|
### 1. Crear archivo de configuración
|
|
|
|
```bash
|
|
# El archivo debe estar en config/secrets.env
|
|
# Usa este template:
|
|
```
|
|
|
|
```env
|
|
# Exchange (para datos públicos NO necesitas API keys)
|
|
EXCHANGE_NAME=binance
|
|
API_KEY=
|
|
API_SECRET=
|
|
|
|
# Database
|
|
DB_HOST=localhost
|
|
DB_PORT=5432
|
|
DB_NAME=trading_bot
|
|
DB_USER=trading_user
|
|
DB_PASSWORD=tu_password_aqui
|
|
|
|
# Redis (opcional)
|
|
REDIS_HOST=localhost
|
|
REDIS_PORT=6379
|
|
REDIS_DB=0
|
|
|
|
# General
|
|
ENVIRONMENT=development
|
|
LOG_LEVEL=INFO
|
|
```
|
|
|
|
### 2. Configurar símbolos y timeframes
|
|
|
|
Edita `config/settings.yaml` para personalizar:
|
|
|
|
```yaml
|
|
trading:
|
|
symbols:
|
|
- BTC/USDT
|
|
- ETH/USDT
|
|
- BNB/USDT
|
|
timeframes:
|
|
- 1h
|
|
- 4h
|
|
- 1d
|
|
|
|
data:
|
|
fetch_interval: 60
|
|
historical_days: 120
|
|
max_retries: 3
|
|
```
|
|
|
|
## 🚀 Uso
|
|
|
|
### Demo rápido (verificar instalación)
|
|
|
|
```bash
|
|
python main.py
|
|
```
|
|
|
|
Este script:
|
|
- Descarga 1 día de BTC/USDT
|
|
- Muestra el pipeline completo
|
|
- Guarda en PostgreSQL
|
|
- Muestra estadísticas
|
|
|
|
### Descarga masiva de datos
|
|
|
|
```bash
|
|
python download_data.py
|
|
```
|
|
|
|
Este script descarga:
|
|
- Múltiples símbolos configurables
|
|
- Múltiples timeframes
|
|
- Días históricos configurables
|
|
- Muestra progreso en tiempo real
|
|
- Previene duplicados automáticamente
|
|
|
|
**Personalizar descarga:**
|
|
Edita `download_data.py` líneas ~28-45:
|
|
|
|
```python
|
|
symbols = [
|
|
'BTC/USDT',
|
|
'ETH/USDT',
|
|
# Añade más aquí
|
|
]
|
|
|
|
timeframes = ['1h', '4h', '1d']
|
|
days_back = 120 # Cambia aquí
|
|
```
|
|
|
|
### Uso programático
|
|
|
|
```python
|
|
from src.data.fetcher import DataFetcher
|
|
from src.data.processor import DataProcessor
|
|
from src.data.storage import StorageManager
|
|
|
|
# Inicializar
|
|
fetcher = DataFetcher('binance')
|
|
processor = DataProcessor()
|
|
storage = StorageManager(...)
|
|
|
|
# Descargar
|
|
df = fetcher.fetch_historical('BTC/USDT', timeframe='1h', days=30)
|
|
|
|
# Procesar
|
|
df_clean = processor.clean_data(df)
|
|
df_clean = processor.calculate_returns(df_clean)
|
|
|
|
# Guardar
|
|
storage.save_ohlcv(df_clean)
|
|
```
|
|
|
|
## 📁 Estructura del Proyecto
|
|
|
|
```
|
|
trading-bot/
|
|
├── config/ # Configuración
|
|
│ ├── settings.yaml # Configuración general
|
|
│ └── secrets.env # Credenciales (NO subir a git)
|
|
│
|
|
├── src/ # Código fuente
|
|
│ ├── data/ # Módulo de datos
|
|
│ │ ├── __init__.py
|
|
│ │ ├── fetcher.py # Descarga desde exchanges
|
|
│ │ ├── processor.py # Limpieza y procesamiento
|
|
│ │ └── storage.py # PostgreSQL + Redis
|
|
│ │
|
|
│ ├── backtest/ # Motor de backtesting (próximo)
|
|
│ ├── strategies/ # Estrategias de trading (próximo)
|
|
│ ├── ml/ # Machine Learning (futuro)
|
|
│ └── utils/ # Utilidades
|
|
│ └── logger.py # Sistema de logging
|
|
│
|
|
├── tests/ # Tests unitarios
|
|
│ └── test_data.py
|
|
│
|
|
├── data/ # Datos locales
|
|
│ ├── historical/ # Backups (futuro)
|
|
│ └── exports/ # Exportaciones (futuro)
|
|
│
|
|
├── logs/ # Archivos de log
|
|
│ ├── trading_bot_*.log
|
|
│ └── errors_*.log
|
|
│
|
|
├── main.py # Demo/testing
|
|
├── download_data.py # Descarga masiva
|
|
├── requirements.txt # Dependencias
|
|
├── .gitignore
|
|
└── README.md
|
|
```
|
|
|
|
## 🗄️ Base de Datos
|
|
|
|
### Ubicación de PostgreSQL
|
|
|
|
```bash
|
|
# Ver ubicación de los datos
|
|
sudo -u postgres psql -c "SHOW data_directory;"
|
|
# Típicamente: /var/lib/postgresql/16/main
|
|
```
|
|
|
|
### Gestión del servicio PostgreSQL
|
|
|
|
**Comandos básicos:**
|
|
```bash
|
|
# Iniciar PostgreSQL
|
|
sudo systemctl start postgresql
|
|
|
|
# Detener PostgreSQL
|
|
sudo systemctl stop postgresql
|
|
|
|
# Reiniciar PostgreSQL
|
|
sudo systemctl restart postgresql
|
|
|
|
# Ver estado
|
|
sudo systemctl status postgresql
|
|
|
|
# Habilitar inicio automático al arrancar el sistema
|
|
sudo systemctl enable postgresql
|
|
|
|
# Deshabilitar inicio automático
|
|
sudo systemctl disable postgresql
|
|
|
|
# Verificar si está habilitado
|
|
systemctl is-enabled postgresql
|
|
```
|
|
|
|
**Nota:** Por defecto, después de la instalación PostgreSQL está configurado para iniciar automáticamente. Si prefieres iniciarlo manualmente cada vez:
|
|
```bash
|
|
sudo systemctl disable postgresql
|
|
```
|
|
|
|
### Tabla OHLCV (estructura)
|
|
|
|
```sql
|
|
CREATE TABLE ohlcv (
|
|
id SERIAL PRIMARY KEY,
|
|
timestamp TIMESTAMP NOT NULL,
|
|
symbol VARCHAR(20) NOT NULL,
|
|
timeframe VARCHAR(10) NOT NULL,
|
|
open FLOAT NOT NULL,
|
|
high FLOAT NOT NULL,
|
|
low FLOAT NOT NULL,
|
|
close FLOAT NOT NULL,
|
|
volume FLOAT NOT NULL,
|
|
returns FLOAT, -- Retornos simples
|
|
log_returns FLOAT, -- Retornos logarítmicos
|
|
CONSTRAINT unique_ohlcv UNIQUE (symbol, timeframe, timestamp)
|
|
);
|
|
|
|
-- Índices para queries rápidas
|
|
CREATE INDEX idx_symbol_timeframe_timestamp ON ohlcv(symbol, timeframe, timestamp);
|
|
CREATE INDEX idx_timestamp ON ohlcv(timestamp);
|
|
```
|
|
|
|
### Consultas útiles
|
|
|
|
```sql
|
|
-- Conectar a la base de datos
|
|
psql -U trading_user -d trading_bot -h localhost
|
|
|
|
-- Ver todas las tablas
|
|
\dt
|
|
|
|
-- Contar registros totales
|
|
SELECT COUNT(*) FROM ohlcv;
|
|
|
|
-- Ver datos disponibles por símbolo
|
|
SELECT
|
|
symbol,
|
|
timeframe,
|
|
COUNT(*) as registros,
|
|
MIN(timestamp) as desde,
|
|
MAX(timestamp) as hasta
|
|
FROM ohlcv
|
|
GROUP BY symbol, timeframe
|
|
ORDER BY symbol, timeframe;
|
|
|
|
-- Ver últimos 10 registros de BTC
|
|
SELECT * FROM ohlcv
|
|
WHERE symbol = 'BTC/USDT' AND timeframe = '1h'
|
|
ORDER BY timestamp DESC
|
|
LIMIT 10;
|
|
|
|
-- Estadísticas de retornos
|
|
SELECT
|
|
symbol,
|
|
timeframe,
|
|
AVG(returns) as retorno_medio,
|
|
STDDEV(returns) as volatilidad,
|
|
MIN(returns) as peor_retorno,
|
|
MAX(returns) as mejor_retorno
|
|
FROM ohlcv
|
|
WHERE returns IS NOT NULL
|
|
GROUP BY symbol, timeframe;
|
|
```
|
|
|
|
### Backup de la base de datos
|
|
|
|
```bash
|
|
# Backup completo
|
|
pg_dump -U trading_user -d trading_bot -h localhost > backup_$(date +%Y%m%d).sql
|
|
|
|
# Backup solo tabla ohlcv
|
|
pg_dump -U trading_user -d trading_bot -h localhost -t ohlcv > backup_ohlcv.sql
|
|
|
|
# Restaurar desde backup
|
|
psql -U trading_user -d trading_bot -h localhost < backup.sql
|
|
```
|
|
|
|
## 📜 Scripts Disponibles
|
|
|
|
### `main.py` - Demo y Testing
|
|
|
|
```bash
|
|
python main.py
|
|
```
|
|
|
|
**Uso:** Verificar que todo funciona correctamente
|
|
**Descarga:** 1 símbolo, 1 timeframe, pocos días
|
|
**Muestra:** Pipeline completo con estadísticas detalladas
|
|
|
|
### `download_data.py` - Descarga Masiva
|
|
|
|
```bash
|
|
python download_data.py
|
|
```
|
|
|
|
**Uso:** Llenar base de datos con datos históricos
|
|
**Configurable:** Símbolos, timeframes, días
|
|
**Características:**
|
|
- Progreso en tiempo real
|
|
- Prevención de duplicados
|
|
- Manejo de errores robusto
|
|
- Resumen final con estadísticas
|
|
|
|
## 🧪 Testing
|
|
|
|
### Ejecutar todos los tests
|
|
|
|
```bash
|
|
pytest tests/ -v
|
|
```
|
|
|
|
### Tests con cobertura
|
|
|
|
```bash
|
|
pytest tests/ --cov=src --cov-report=html
|
|
# Ver reporte en htmlcov/index.html
|
|
```
|
|
|
|
### Test específico
|
|
|
|
```bash
|
|
pytest tests/test_data.py::TestDataProcessor::test_clean_data_removes_duplicates -v
|
|
```
|
|
|
|
## 🗺️ Roadmap
|
|
|
|
### ✅ Fase 1: Infraestructura de Datos (COMPLETADO)
|
|
- Sistema de descarga robusto
|
|
- Almacenamiento optimizado
|
|
- Procesamiento de datos
|
|
|
|
### 🔄 Fase 2: Backtesting (PRÓXIMO - Semanas 3-4)
|
|
- Motor de backtesting
|
|
- Estrategia simple (moving average crossover)
|
|
- Métricas de performance
|
|
- Visualizaciones
|
|
|
|
### 📅 Fase 3: Estrategias Avanzadas (Semanas 5-8)
|
|
- Indicadores técnicos
|
|
- Machine Learning básico
|
|
- Optimización de parámetros
|
|
|
|
### 📅 Fase 4: Trading Real (Semanas 9-12)
|
|
- Paper trading
|
|
- Gestión de riesgo
|
|
- Ejecución de órdenes
|
|
- Monitoreo en tiempo real
|
|
|
|
### 📅 Fase 5: Producción (Futuro)
|
|
- Dashboard web
|
|
- Alertas y notificaciones
|
|
- Multi-exchange
|
|
- Despliegue en servidor
|
|
|
|
## 🐛 Troubleshooting
|
|
|
|
### Error: "No se puede conectar a PostgreSQL"
|
|
|
|
```bash
|
|
# Verificar que está corriendo
|
|
sudo systemctl status postgresql
|
|
|
|
# Reiniciar si es necesario
|
|
sudo systemctl restart postgresql
|
|
|
|
# Verificar credenciales en config/secrets.env
|
|
```
|
|
|
|
### Error: "Invalid Api-Key ID"
|
|
|
|
**Solución:** Para datos públicos NO necesitas API keys. Deja vacíos `API_KEY` y `API_SECRET` en `config/secrets.env`.
|
|
|
|
### Error: "column does not exist"
|
|
|
|
**Solución:** Recrear la tabla:
|
|
|
|
```sql
|
|
DROP TABLE IF EXISTS ohlcv CASCADE;
|
|
```
|
|
|
|
Luego ejecutar `python main.py` para recrearla.
|
|
|
|
### Error: "duplicate key value violates unique constraint"
|
|
|
|
**Solución:** Esto es normal y esperado. El sistema previene automáticamente duplicados. Si quieres limpiar duplicados existentes:
|
|
|
|
```sql
|
|
DELETE FROM ohlcv a USING ohlcv b
|
|
WHERE a.id > b.id
|
|
AND a.symbol = b.symbol
|
|
AND a.timeframe = b.timeframe
|
|
AND a.timestamp = b.timestamp;
|
|
```
|
|
|
|
### Redis no está disponible
|
|
|
|
**No es crítico.** El bot funciona sin Redis, solo perderás caché. Logs mostrarán: "Continuando sin caché."
|
|
|
|
Para instalar Redis:
|
|
```bash
|
|
sudo apt install redis-server
|
|
sudo systemctl start redis
|
|
```
|
|
|
|
### Downloads muy lentos
|
|
|
|
- Verifica tu conexión a internet
|
|
- El exchange puede tener rate limiting
|
|
- Para Binance sin API keys: ~1000 requests/min
|
|
|
|
### La descarga se queda colgada
|
|
|
|
- Presiona `Ctrl+C` para cancelar
|
|
- Revisa logs en `logs/trading_bot_*.log`
|
|
- Verifica que el exchange esté accesible
|
|
|
|
## 📝 Notas Importantes
|
|
|
|
### ⚠️ Advertencia Legal
|
|
|
|
Este bot es para **fines educativos y de investigación**. El trading conlleva riesgo financiero significativo.
|
|
|
|
**NO ejecutes trading real sin:**
|
|
1. ✅ Backtesting exhaustivo (mínimo 3-5 años de datos)
|
|
2. ✅ Paper trading extensivo (varios meses)
|
|
3. ✅ Gestión de riesgo robusta y probada
|
|
4. ✅ Comprensión completa del código y estrategias
|
|
5. ✅ Capital que puedas permitirte perder
|
|
|
|
### 🔒 Seguridad
|
|
|
|
- **NUNCA** subas `config/secrets.env` a git
|
|
- Usa contraseñas fuertes para PostgreSQL
|
|
- En producción, usa variables de entorno del sistema
|
|
- Limita permisos de archivos sensibles: `chmod 600 config/secrets.env`
|
|
|
|
### 💾 Portabilidad (Futuro)
|
|
|
|
Actualmente usa PostgreSQL (requiere instalación en cada máquina).
|
|
|
|
**Plan futuro:** Script de exportación a SQLite para portabilidad completa:
|
|
```bash
|
|
python export_to_portable.py # Generará data/trading_bot.db
|
|
```
|
|
|
|
Esto permitirá copiar todo el proyecto en USB y ejecutar en cualquier PC.
|
|
|
|
## 🤝 Contribuir
|
|
|
|
Este es un proyecto personal de aprendizaje. Sugerencias y mejoras son bienvenidas.
|
|
|
|
## 📄 Licencia
|
|
|
|
MIT License - Usar bajo tu propio riesgo
|
|
|
|
## 📧 Contacto
|
|
|
|
Para dudas sobre el código o siguientes fases de desarrollo, consulta conmigo.
|
|
|
|
---
|
|
|
|
**Versión actual:** 0.2.0 (Semanas 1-2 completadas, Semanas 3-4 en preparación)
|
|
**Última actualización:** Enero 2026
|
|
**Python:** 3.12.3
|
|
**PostgreSQL:** 16+
|
|
**Datos:** 5 símbolos, 3 timeframes, 120 días (~54k registros) |