# Auto-Trading System - LLM Agent

## Overview

The Auto-Trading system enables the LLM Agent to autonomously analyze ML signals, evaluate AMD (Accumulation/Manipulation/Distribution) phases, and make informed trading decisions.

## Features

### 1. Automated Decision Making
- Analyzes ML signals from the ML Engine
- Evaluates AMD phase for market context
- Makes BUY/SELL/HOLD decisions with confidence scores
- Calculates optimal position sizes based on risk parameters

### 2. Risk Management
- Automatic TP/SL calculation based on ML signals
- Position sizing based on account size and risk percentage
- Maximum position limits to prevent overexposure
- Confidence threshold filtering

### 3. Safety Features
- Paper trading mode by default
- Optional user confirmation before execution
- Decision logging for audit trail
- Configurable monitoring intervals

### 4. Monitoring Loop
- Background task monitors configured symbols
- Periodic checks every N minutes (configurable)
- Automatic decision generation on opportunities
- Non-blocking async implementation

## Architecture

### Models (`src/models/auto_trade.py`)

#### TradeDecision
Represents an automated trading decision:
```python
{
    "symbol": "BTC/USD",
    "action": "BUY",  # BUY, SELL, or HOLD
    "confidence": 0.85,  # 0-1
    "reasoning": "Strong bullish signal during accumulation",
    "entry_price": 45000.0,
    "take_profit": 47500.0,
    "stop_loss": 44000.0,
    "position_size": 0.5,
    "ml_signal": {...},
    "amd_phase": "accumulation"
}
```

#### AutoTradeConfig
Configuration for auto-trading:
```python
{
    "user_id": "user_123",
    "enabled": true,
    "symbols": ["BTC/USD", "ETH/USD"],
    "max_risk_percent": 1.5,
    "min_confidence": 0.75,
    "paper_trading": true,
    "require_confirmation": true,
    "max_open_positions": 3,
    "check_interval_minutes": 5
}
```

### Tools (`src/tools/auto_trading.py`)

#### AutoTradeDecisionTool
Core decision-making tool that:
1. Fetches ML signal from ML Engine
2. Gets AMD phase analysis
3. Retrieves current market data
4. Applies decision matrix logic
5. Calculates position size and TP/SL

#### GetAMDPhaseTool
Analyzes AMD phase for a symbol:
- Accumulation: Smart money buying (good for longs)
- Manipulation: High volatility (trade with caution)
- Distribution: Smart money selling (good for shorts)

### Service (`src/services/auto_trade_service.py`)

#### AutoTradeService
Manages auto-trading operations:
- Configuration management
- Background monitoring loop
- Decision logging
- Trade execution coordination

### API Endpoints (`src/api/auto_trade_routes.py`)

#### Configuration Endpoints

**POST /api/v1/auto-trade/config**
Set or update auto-trade configuration
```json
{
    "config": {
        "user_id": "user_123",
        "enabled": true,
        "symbols": ["BTC/USD"],
        "max_risk_percent": 1.5,
        "min_confidence": 0.75
    }
}
```

**GET /api/v1/auto-trade/config/{user_id}**
Get current configuration

**GET /api/v1/auto-trade/status/{user_id}**
Get current status

#### Control Endpoints

**POST /api/v1/auto-trade/enable/{user_id}**
Quick enable auto-trading

**POST /api/v1/auto-trade/disable/{user_id}**
Quick disable auto-trading

#### Decision Management

**GET /api/v1/auto-trade/decisions/{user_id}**
Get decision logs
- Query params: `limit` (default: 50), `executed_only` (default: false)

**GET /api/v1/auto-trade/pending/{user_id}**
Get pending (unexecuted) decisions

**POST /api/v1/auto-trade/decisions/{user_id}/confirm**
Confirm and execute a pending decision
```json
{
    "log_id": "decision_123"
}
```

**POST /api/v1/auto-trade/decisions/{user_id}/cancel**
Cancel a pending decision
```json
{
    "log_id": "decision_123"
}
```

## Decision Logic

### Decision Matrix

The system uses a decision matrix based on ML signals and AMD phases:

| ML Signal | AMD Phase | Decision | Confidence |
|-----------|-----------|----------|------------|
| Bullish | Accumulation | BUY | High (0.95x) |
| Bullish | Manipulation | BUY | Medium (0.70x) |
| Bullish | Distribution | HOLD | Low (0.30) |
| Bearish | Distribution | SELL | High (0.95x) |
| Bearish | Manipulation | SELL | Medium (0.70x) |
| Bearish | Accumulation | HOLD | Low (0.30) |
| Neutral | Any | HOLD | None (0.0) |

### Position Sizing

Position size is calculated using:
```
Risk Amount = Account Size × (Risk % / 100)
Risk Per Unit = |Entry Price - Stop Loss|
Position Size = Risk Amount / Risk Per Unit
```

Maximum position size is capped at 20% of account value.

## Enhanced Execute Trade Tool

The `execute_trade` tool has been enhanced with:

### ML Integration
- Automatic TP/SL calculation from ML signals
- Falls back to manual values if provided
- Fetches current market price

### Risk/Reward Analysis
```python
{
    "risk_amount": 500.0,
    "reward_amount": 2500.0,
    "risk_reward_ratio": 5.0,
    "risk_percent": 1.11,
    "reward_percent": 5.56
}
```

### Modes
- **Paper Trading**: Safe simulation mode (default)
- **Live Trading**: Real execution (requires explicit enable)
- **Confirmation Required**: Manual approval (default: true)
- **Auto-Execute**: Direct execution for auto-trading (confirmation: false)

## Usage Examples

### 1. Configure Auto-Trading

```bash
curl -X POST http://localhost:8003/api/v1/auto-trade/config \
  -H "Content-Type: application/json" \
  -d '{
    "config": {
      "user_id": "user_123",
      "enabled": true,
      "symbols": ["BTC/USD", "ETH/USD"],
      "max_risk_percent": 1.0,
      "min_confidence": 0.75,
      "paper_trading": true,
      "require_confirmation": false,
      "max_open_positions": 3,
      "check_interval_minutes": 5
    }
  }'
```

### 2. Check Status

```bash
curl http://localhost:8003/api/v1/auto-trade/status/user_123
```

### 3. View Pending Decisions

```bash
curl http://localhost:8003/api/v1/auto-trade/pending/user_123
```

### 4. Confirm Decision

```bash
curl -X POST http://localhost:8003/api/v1/auto-trade/decisions/user_123/confirm \
  -H "Content-Type: application/json" \
  -d '{"log_id": "decision_abc123"}'
```

### 5. Disable Auto-Trading

```bash
curl -X POST http://localhost:8003/api/v1/auto-trade/disable/user_123
```

## Testing

Run tests with pytest:

```bash
cd /home/isem/workspace/projects/trading-platform/apps/llm-agent
pytest tests/test_auto_trading.py -v
```

Test coverage includes:
- Model validation
- Configuration management
- Service operations
- Decision lifecycle
- Monitoring control

## Safety Considerations

### Before Production

1. **API Integration**: Complete integration with backend trading API
2. **Database Persistence**: Store decision logs in database (currently in-memory)
3. **User Authentication**: Implement proper user authentication
4. **Rate Limiting**: Add rate limiting on API endpoints
5. **Error Handling**: Enhanced error handling and retry logic
6. **Monitoring**: Set up monitoring and alerting
7. **Audit Logs**: Comprehensive audit logging
8. **Testing**: Extensive integration and load testing

### Security

- Never store API keys in code
- Validate all user inputs
- Implement proper authentication/authorization
- Use HTTPS in production
- Rate limit API calls
- Sanitize all database queries

### Risk Management

- Start with paper trading only
- Test thoroughly before enabling live trading
- Set conservative position size limits
- Monitor system performance continuously
- Have kill switch to disable all auto-trading
- Regular reviews of decision logs

## Integration with ML Engine

The system expects the following ML Engine endpoints:

### GET /api/v1/signals/{symbol}
Returns ML trading signal:
```json
{
    "direction": "bullish",
    "confidence": 0.87,
    "entry_price": 45000.0,
    "take_profit": 47500.0,
    "stop_loss": 44000.0,
    "risk_reward_ratio": 2.5
}
```

### GET /api/v1/amd/phase/{symbol}
Returns AMD phase analysis:
```json
{
    "phase": "accumulation",
    "confidence": 0.85,
    "indicators": {
        "volume_profile": "accumulating",
        "price_action": "consolidation"
    }
}
```

## Future Enhancements

1. **Multi-timeframe Analysis**: Consider multiple timeframes for decisions
2. **Portfolio Balancing**: Automatic portfolio rebalancing
3. **Advanced Filters**: Additional filters (news sentiment, macro indicators)
4. **Backtesting**: Historical performance testing
5. **Performance Analytics**: Detailed performance metrics and reporting
6. **Machine Learning**: Learn from past decisions to improve
7. **Notifications**: Push notifications for important decisions
8. **Stop Management**: Trailing stops and dynamic adjustment

## Troubleshooting

### Monitoring Not Starting
- Check that configuration is properly set
- Verify `enabled: true` in config
- Check logs for error messages

### No Decisions Being Made
- Verify symbols are correct
- Check ML Engine connectivity
- Review confidence threshold settings
- Check min_confidence vs actual signal confidence

### Decisions Not Executing
- Verify require_confirmation setting
- Check pending decisions queue
- Review execution logs

## Support

For issues or questions:
1. Check logs in `/var/log/llm-agent/`
2. Review decision logs via API
3. Check system status endpoint
4. Verify ML Engine connectivity

## License

OrbiQuant IA Trading Platform - Proprietary
