336 lines
7.3 KiB
Markdown
336 lines
7.3 KiB
Markdown
# OrbiQuant Trading Agents
|
|
|
|
Sistema de agentes de trading automático con diferentes perfiles de riesgo.
|
|
|
|
## Agentes Disponibles
|
|
|
|
### Atlas - El Guardián (Conservador)
|
|
- **Perfil:** Conservador
|
|
- **Target mensual:** 3-5%
|
|
- **Max Drawdown:** 5%
|
|
- **Pares:** BTC/USDT, ETH/USDT
|
|
- **Estrategias:** Mean Reversion, Grid Trading
|
|
- **Max Posiciones:** 3
|
|
- **Trades/día:** 2-5
|
|
|
|
### Orion - El Explorador (Moderado)
|
|
- **Perfil:** Moderado
|
|
- **Target mensual:** 5-10%
|
|
- **Max Drawdown:** 10%
|
|
- **Pares:** Top 10 cryptos
|
|
- **Estrategias:** Trend Following, Momentum
|
|
- **Max Posiciones:** 5
|
|
- **Trades/día:** 5-15
|
|
|
|
### Nova - La Estrella (Agresivo)
|
|
- **Perfil:** Agresivo
|
|
- **Target mensual:** 10%+
|
|
- **Max Drawdown:** 20%
|
|
- **Pares:** Todos disponibles
|
|
- **Estrategias:** Momentum, Scalping, Trend Following
|
|
- **Max Posiciones:** 10
|
|
- **Trades/día:** 20+
|
|
|
|
## Estructura del Proyecto
|
|
|
|
```
|
|
apps/trading-agents/
|
|
├── src/
|
|
│ ├── agents/
|
|
│ │ ├── base.py # BaseAgent class
|
|
│ │ ├── atlas.py # Atlas agent (Conservative)
|
|
│ │ ├── orion.py # Orion agent (Moderate)
|
|
│ │ └── nova.py # Nova agent (Aggressive)
|
|
│ ├── strategies/
|
|
│ │ ├── base.py # BaseStrategy
|
|
│ │ ├── mean_reversion.py # Mean reversion strategy
|
|
│ │ ├── grid_trading.py # Grid trading strategy
|
|
│ │ ├── trend_following.py # Trend following strategy
|
|
│ │ └── momentum.py # Momentum strategy
|
|
│ ├── execution/
|
|
│ │ └── risk_manager.py # Risk management
|
|
│ ├── exchange/
|
|
│ │ └── binance_client.py # Binance API client
|
|
│ ├── signals/
|
|
│ │ └── ml_consumer.py # ML signals consumer
|
|
│ └── api/
|
|
│ └── main.py # FastAPI app
|
|
├── config/
|
|
│ ├── agents.yaml # Agents configuration
|
|
│ ├── strategies.yaml # Strategies configuration
|
|
│ └── risk.yaml # Risk parameters
|
|
├── requirements.txt
|
|
├── Dockerfile
|
|
└── docker-compose.yml
|
|
```
|
|
|
|
## Instalación
|
|
|
|
### 1. Requisitos
|
|
- Python 3.11+
|
|
- Docker (opcional)
|
|
- Binance Testnet API keys (para paper trading)
|
|
|
|
### 2. Instalación local
|
|
|
|
```bash
|
|
cd apps/trading-agents
|
|
|
|
# Crear entorno virtual
|
|
python -m venv venv
|
|
source venv/bin/activate # Linux/Mac
|
|
# o
|
|
venv\Scripts\activate # Windows
|
|
|
|
# Instalar dependencias
|
|
pip install -r requirements.txt
|
|
```
|
|
|
|
### 3. Configuración
|
|
|
|
Crear archivo `.env`:
|
|
|
|
```bash
|
|
# Binance API
|
|
BINANCE_API_KEY=your_testnet_api_key
|
|
BINANCE_API_SECRET=your_testnet_api_secret
|
|
BINANCE_TESTNET=true
|
|
|
|
# ML Engine
|
|
ML_ENGINE_URL=http://localhost:8000
|
|
ML_ENGINE_API_KEY=dev_ml_key
|
|
|
|
# Database
|
|
DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/orbiquant
|
|
|
|
# API
|
|
API_PORT=8003
|
|
API_HOST=0.0.0.0
|
|
```
|
|
|
|
## Uso
|
|
|
|
### Iniciar el servicio
|
|
|
|
```bash
|
|
# Local
|
|
python -m src.api.main
|
|
|
|
# Docker
|
|
docker-compose up -d
|
|
```
|
|
|
|
### API Endpoints
|
|
|
|
#### Listar agentes
|
|
```bash
|
|
curl http://localhost:8003/agents
|
|
```
|
|
|
|
#### Iniciar un agente
|
|
```bash
|
|
curl -X POST http://localhost:8003/agents/atlas/start \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"agent_name": "atlas",
|
|
"initial_equity": 1000.0
|
|
}'
|
|
```
|
|
|
|
#### Ver estado del agente
|
|
```bash
|
|
curl http://localhost:8003/agents/atlas/status
|
|
```
|
|
|
|
#### Enviar señal de trading
|
|
```bash
|
|
curl -X POST http://localhost:8003/agents/atlas/signal \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"agent_name": "atlas",
|
|
"symbol": "BTCUSDT",
|
|
"action": "buy",
|
|
"confidence": 0.85,
|
|
"price": 45000.0
|
|
}'
|
|
```
|
|
|
|
#### Ver posiciones abiertas
|
|
```bash
|
|
curl http://localhost:8003/agents/atlas/positions
|
|
```
|
|
|
|
#### Ver métricas detalladas
|
|
```bash
|
|
curl http://localhost:8003/agents/atlas/metrics
|
|
```
|
|
|
|
#### Pausar agente
|
|
```bash
|
|
curl -X POST http://localhost:8003/agents/atlas/pause
|
|
```
|
|
|
|
#### Reanudar agente
|
|
```bash
|
|
curl -X POST http://localhost:8003/agents/atlas/resume
|
|
```
|
|
|
|
#### Detener agente
|
|
```bash
|
|
curl -X POST http://localhost:8003/agents/atlas/stop
|
|
```
|
|
|
|
## Paper Trading con Binance Testnet
|
|
|
|
### 1. Obtener API Keys de Testnet
|
|
|
|
1. Ir a [Binance Testnet](https://testnet.binancefuture.com/)
|
|
2. Crear cuenta de testnet
|
|
3. Generar API keys
|
|
4. Agregar keys al archivo `.env`
|
|
|
|
### 2. Configurar agente para testnet
|
|
|
|
```python
|
|
from src.exchange.binance_client import BinanceClient
|
|
from src.agents.atlas import AtlasAgent
|
|
|
|
# Crear cliente de Binance
|
|
async with BinanceClient(
|
|
api_key="your_testnet_key",
|
|
api_secret="your_testnet_secret",
|
|
testnet=True
|
|
) as client:
|
|
# Verificar conectividad
|
|
healthy = await client.health_check()
|
|
print(f"Binance Testnet: {'OK' if healthy else 'FAIL'}")
|
|
|
|
# Iniciar agente
|
|
agent = AtlasAgent(equity=1000.0)
|
|
await agent.start()
|
|
```
|
|
|
|
## Estrategias
|
|
|
|
### Mean Reversion
|
|
- Compra cuando precio < SMA - N*STD
|
|
- Vende cuando precio > SMA + N*STD
|
|
- Ideal para mercados laterales
|
|
|
|
### Grid Trading
|
|
- Crea grid de niveles de precio
|
|
- Compra en niveles bajos, vende en niveles altos
|
|
- Ideal para mercados con rango definido
|
|
|
|
### Trend Following
|
|
- Sigue tendencias usando EMAs y MACD
|
|
- Compra en tendencia alcista, vende en bajista
|
|
- Ideal para mercados con tendencia
|
|
|
|
### Momentum
|
|
- Detecta movimientos fuertes con ROC
|
|
- Confirma con volumen
|
|
- Ideal para breakouts
|
|
|
|
## Gestión de Riesgo
|
|
|
|
### Límites por Agente
|
|
|
|
| Agente | Max DD | Max Pos | Pos Size | SL | TP |
|
|
|--------|--------|---------|----------|-----|-----|
|
|
| Atlas | 5% | 3 | 10% | 2% | 3% |
|
|
| Orion | 10% | 5 | 15% | 3% | 6% |
|
|
| Nova | 20% | 10 | 20% | 4% | 8% |
|
|
|
|
### Circuit Breakers
|
|
|
|
- **Max pérdidas consecutivas:** 5 (pausa 1h)
|
|
- **Drawdown rápido:** 3% en 15min (pausa 2h)
|
|
- **Kill switch:** Activado en 10% pérdida diaria
|
|
|
|
## Monitoreo
|
|
|
|
### Logs
|
|
|
|
Los logs se guardan en:
|
|
- `logs/trading-agents.log`
|
|
- `logs/agents/atlas.log`
|
|
- `logs/agents/orion.log`
|
|
- `logs/agents/nova.log`
|
|
|
|
### Métricas
|
|
|
|
Cada agente reporta:
|
|
- Total trades
|
|
- Win rate
|
|
- Profit factor
|
|
- Sharpe ratio
|
|
- Max drawdown
|
|
- Current drawdown
|
|
- Posiciones abiertas
|
|
|
|
## Testing
|
|
|
|
```bash
|
|
# Run tests
|
|
pytest tests/
|
|
|
|
# Run with coverage
|
|
pytest --cov=src tests/
|
|
|
|
# Run specific test
|
|
pytest tests/test_agents.py::test_atlas_agent
|
|
```
|
|
|
|
## Desarrollo
|
|
|
|
### Agregar nueva estrategia
|
|
|
|
1. Crear archivo en `src/strategies/`
|
|
2. Heredar de `BaseStrategy`
|
|
3. Implementar método `generate_signal()`
|
|
|
|
```python
|
|
from src.strategies.base import BaseStrategy, Signal, SignalType
|
|
|
|
class MyStrategy(BaseStrategy):
|
|
def generate_signal(self, data):
|
|
# Tu lógica aquí
|
|
return Signal(
|
|
symbol="BTCUSDT",
|
|
signal_type=SignalType.BUY,
|
|
confidence=0.8,
|
|
entry_price=45000.0
|
|
)
|
|
```
|
|
|
|
### Agregar nuevo agente
|
|
|
|
1. Crear archivo en `src/agents/`
|
|
2. Heredar de `BaseAgent`
|
|
3. Implementar métodos requeridos
|
|
|
|
## Troubleshooting
|
|
|
|
### Error: "Binance API error"
|
|
- Verificar API keys
|
|
- Verificar que estés usando testnet keys con `BINANCE_TESTNET=true`
|
|
|
|
### Error: "Max drawdown exceeded"
|
|
- El agente se pausó automáticamente
|
|
- Verificar equity y performance
|
|
- Reanudar con `/resume` cuando esté listo
|
|
|
|
### Error: "Insufficient data"
|
|
- Las estrategias requieren datos históricos
|
|
- Esperar a que se acumule suficiente data
|
|
|
|
## Licencia
|
|
|
|
Propietario - OrbiQuant IA
|
|
|
|
## Contacto
|
|
|
|
- Email: support@orbiquant.ai
|
|
- Docs: https://docs.orbiquant.ai
|