322 lines
7.9 KiB
Markdown
322 lines
7.9 KiB
Markdown
# Paper Trading Guide
|
|
|
|
Guía completa para paper trading con Binance Testnet
|
|
|
|
## 1. Configuración de Binance Testnet
|
|
|
|
### Paso 1: Crear cuenta en Testnet
|
|
|
|
1. Ir a [https://testnet.binancefuture.com/](https://testnet.binancefuture.com/)
|
|
2. Hacer clic en "Register" (esquina superior derecha)
|
|
3. Crear cuenta con email (no requiere verificación real)
|
|
4. Iniciar sesión
|
|
|
|
### Paso 2: Obtener API Keys
|
|
|
|
1. Una vez logueado, ir a "API Management"
|
|
2. Hacer clic en "Generate HMAC_SHA256 Key"
|
|
3. Ingresar un nombre (ejemplo: "OrbiQuant Trading Bot")
|
|
4. Copiar el API Key y Secret Key
|
|
5. **IMPORTANTE:** Guardar el Secret Key - solo se muestra una vez
|
|
|
|
### Paso 3: Configurar permisos
|
|
|
|
1. En la configuración de la API key, habilitar:
|
|
- ✓ Enable Reading
|
|
- ✓ Enable Spot & Margin Trading
|
|
- ✓ Enable Futures
|
|
|
|
## 2. Configuración Local
|
|
|
|
### Crear archivo .env
|
|
|
|
```bash
|
|
cd apps/trading-agents
|
|
cp .env.example .env
|
|
```
|
|
|
|
Editar `.env` con tus API keys:
|
|
|
|
```bash
|
|
BINANCE_API_KEY=tu_api_key_aqui
|
|
BINANCE_API_SECRET=tu_secret_key_aqui
|
|
BINANCE_TESTNET=true
|
|
|
|
ML_ENGINE_URL=http://localhost:8000
|
|
ML_ENGINE_API_KEY=dev_ml_key
|
|
|
|
API_PORT=8003
|
|
API_HOST=0.0.0.0
|
|
```
|
|
|
|
## 3. Iniciar el Servicio
|
|
|
|
### Opción A: Local (Python)
|
|
|
|
```bash
|
|
# Activar entorno virtual
|
|
source venv/bin/activate
|
|
|
|
# Instalar dependencias
|
|
pip install -r requirements.txt
|
|
|
|
# Iniciar servicio
|
|
python -m src.api.main
|
|
```
|
|
|
|
### Opción B: Docker
|
|
|
|
```bash
|
|
# Construir imagen
|
|
docker-compose build
|
|
|
|
# Iniciar servicio
|
|
docker-compose up -d
|
|
|
|
# Ver logs
|
|
docker-compose logs -f trading-agents
|
|
```
|
|
|
|
## 4. Testing Básico
|
|
|
|
### Verificar conexión a Binance Testnet
|
|
|
|
```python
|
|
import asyncio
|
|
from src.exchange.binance_client import BinanceClient
|
|
|
|
async def test_connection():
|
|
async with BinanceClient(
|
|
api_key="tu_api_key",
|
|
api_secret="tu_secret_key",
|
|
testnet=True
|
|
) as client:
|
|
# Test 1: Health check
|
|
healthy = await client.health_check()
|
|
print(f"Binance Testnet: {'✓ Connected' if healthy else '✗ Failed'}")
|
|
|
|
# Test 2: Get account info
|
|
account = await client.get_account_info()
|
|
print(f"Account Balance: {account}")
|
|
|
|
# Test 3: Get ticker price
|
|
btc_price = await client.get_ticker_price("BTCUSDT")
|
|
print(f"BTC Price: ${btc_price:.2f}")
|
|
|
|
asyncio.run(test_connection())
|
|
```
|
|
|
|
## 5. Ejecutar Agente con Paper Trading
|
|
|
|
### Atlas Agent (Conservador)
|
|
|
|
```python
|
|
import asyncio
|
|
from src.agents.atlas import AtlasAgent
|
|
from src.exchange.binance_client import BinanceClient
|
|
|
|
async def run_atlas_paper_trading():
|
|
# 1. Crear cliente de Binance
|
|
client = BinanceClient(
|
|
api_key="tu_api_key",
|
|
api_secret="tu_secret_key",
|
|
testnet=True
|
|
)
|
|
|
|
# 2. Verificar balance inicial
|
|
async with client:
|
|
balance = await client.get_balance()
|
|
usdt_balance = next(
|
|
(b for b in balance if b['asset'] == 'USDT'),
|
|
None
|
|
)
|
|
initial_equity = float(usdt_balance['availableBalance'])
|
|
print(f"Initial USDT Balance: ${initial_equity:.2f}")
|
|
|
|
# 3. Crear y iniciar agente
|
|
agent = AtlasAgent(equity=initial_equity)
|
|
await agent.start()
|
|
|
|
print(f"\nAtlas Agent started")
|
|
print(f"Max Drawdown: {agent.config.max_drawdown}%")
|
|
print(f"Position Size: {agent.config.position_size_pct}%")
|
|
print(f"Allowed Pairs: {agent.config.allowed_pairs}")
|
|
|
|
# 4. Simular señal de trading
|
|
btc_price = await client.get_ticker_price("BTCUSDT")
|
|
signal = {
|
|
'symbol': 'BTCUSDT',
|
|
'action': 'buy',
|
|
'confidence': 0.85,
|
|
'price': btc_price
|
|
}
|
|
|
|
print(f"\nProcessing signal: BUY BTCUSDT @ ${btc_price:.2f}")
|
|
await agent.on_signal(signal)
|
|
|
|
# 5. Si el agente abrió posición, ejecutar en Binance Testnet
|
|
if agent.positions:
|
|
pos = agent.positions[0]
|
|
print(f"\nPlacing order on Binance Testnet...")
|
|
|
|
order = await client.place_market_order(
|
|
symbol=pos.symbol,
|
|
side='BUY',
|
|
quantity=pos.quantity
|
|
)
|
|
|
|
print(f"Order placed: {order}")
|
|
|
|
# 6. Mostrar métricas
|
|
metrics = agent.get_metrics()
|
|
print(f"\nAgent Metrics:")
|
|
for key, value in metrics.items():
|
|
print(f" {key}: {value}")
|
|
|
|
await agent.stop()
|
|
|
|
asyncio.run(run_atlas_paper_trading())
|
|
```
|
|
|
|
## 6. Monitoreo en Tiempo Real
|
|
|
|
### Usando la API
|
|
|
|
```bash
|
|
# 1. Iniciar agente
|
|
curl -X POST http://localhost:8003/agents/atlas/start \
|
|
-H "Content-Type: application/json" \
|
|
-d '{"agent_name": "atlas", "initial_equity": 1000.0}'
|
|
|
|
# 2. Ver estado
|
|
curl http://localhost:8003/agents/atlas/status
|
|
|
|
# 3. Ver posiciones
|
|
curl http://localhost:8003/agents/atlas/positions
|
|
|
|
# 4. Ver métricas
|
|
curl http://localhost:8003/agents/atlas/metrics
|
|
```
|
|
|
|
## 7. Testing de Estrategias
|
|
|
|
### Mean Reversion
|
|
|
|
```python
|
|
import asyncio
|
|
import pandas as pd
|
|
from src.strategies.mean_reversion import MeanReversionStrategy
|
|
from src.exchange.binance_client import BinanceClient
|
|
|
|
async def test_mean_reversion():
|
|
# Obtener datos históricos
|
|
async with BinanceClient(
|
|
api_key="tu_key",
|
|
api_secret="tu_secret",
|
|
testnet=True
|
|
) as client:
|
|
# Get klines (candlestick data)
|
|
klines = await client.get_klines("BTCUSDT", "1h", 100)
|
|
|
|
# Convert to DataFrame
|
|
df = pd.DataFrame(klines, columns=[
|
|
'timestamp', 'open', 'high', 'low', 'close',
|
|
'volume', 'close_time', 'quote_volume', 'trades',
|
|
'taker_buy_base', 'taker_buy_quote', 'ignore'
|
|
])
|
|
|
|
df['close'] = df['close'].astype(float)
|
|
df['high'] = df['high'].astype(float)
|
|
df['low'] = df['low'].astype(float)
|
|
|
|
# Test strategy
|
|
strategy = MeanReversionStrategy({
|
|
'sma_period': 20,
|
|
'std_multiplier': 2.0,
|
|
'rsi_period': 14
|
|
})
|
|
|
|
signal = strategy.generate_signal(df)
|
|
|
|
if signal:
|
|
print(f"Signal: {signal.signal_type.value}")
|
|
print(f"Confidence: {signal.confidence:.2f}")
|
|
print(f"Reason: {signal.reason}")
|
|
else:
|
|
print("No signal generated")
|
|
|
|
asyncio.run(test_mean_reversion())
|
|
```
|
|
|
|
## 8. Mejores Prácticas
|
|
|
|
### 1. Empezar con montos pequeños
|
|
```python
|
|
# Usar $100-$1000 para testing
|
|
agent = AtlasAgent(equity=100.0)
|
|
```
|
|
|
|
### 2. Monitorear métricas constantemente
|
|
```python
|
|
# Verificar después de cada trade
|
|
metrics = agent.get_metrics()
|
|
print(f"Win Rate: {metrics['win_rate']:.2f}%")
|
|
print(f"Drawdown: {metrics['current_drawdown']:.2f}%")
|
|
```
|
|
|
|
### 3. Probar cada estrategia individualmente
|
|
```python
|
|
# Test solo Mean Reversion
|
|
agent.config.strategies = ['mean_reversion']
|
|
```
|
|
|
|
### 4. Usar stop loss y take profit
|
|
```python
|
|
# Siempre definir límites
|
|
position = Position(
|
|
symbol="BTCUSDT",
|
|
side="buy",
|
|
quantity=0.01,
|
|
entry_price=45000.0,
|
|
stop_loss=44100.0, # -2%
|
|
take_profit=45900.0 # +2%
|
|
)
|
|
```
|
|
|
|
## 9. Troubleshooting
|
|
|
|
### Error: "Invalid API Key"
|
|
```bash
|
|
# Verificar que las keys sean de Testnet
|
|
# Las keys de producción NO funcionan en testnet
|
|
# Regenerar keys si es necesario
|
|
```
|
|
|
|
### Error: "Insufficient Balance"
|
|
```bash
|
|
# Verificar balance en Binance Testnet
|
|
# El testnet da $100,000 USDT virtuales al registrarse
|
|
# Si se agotó, crear nueva cuenta de testnet
|
|
```
|
|
|
|
### Error: "Symbol not found"
|
|
```bash
|
|
# Verificar que el símbolo sea correcto
|
|
# Formato: "BTCUSDT" (sin espacios ni guiones)
|
|
# Lista de símbolos: client.get_exchange_info()
|
|
```
|
|
|
|
## 10. Recursos Adicionales
|
|
|
|
- [Binance Testnet](https://testnet.binancefuture.com/)
|
|
- [Binance API Docs](https://binance-docs.github.io/apidocs/futures/en/)
|
|
- [Trading Agents README](README.md)
|
|
|
|
## Notas Importantes
|
|
|
|
1. **NO usar API keys de producción en testnet**
|
|
2. **Testnet usa datos de mercado reales pero dinero virtual**
|
|
3. **Las órdenes en testnet NO afectan tu dinero real**
|
|
4. **Probar exhaustivamente antes de pasar a producción**
|
|
5. **Siempre usar límites de riesgo conservadores**
|