# Configuration Module

The configuration module provides a robust, type-safe configuration management system for the Openfund Agent.

## Features

- **YAML-based Configuration**: Easy-to-read and maintain configuration files
- **Environment Variable Substitution**: Secure credential management using `${VAR_NAME}` syntax
- **Type Safety**: Strongly-typed configuration objects using Python dataclasses
- **Validation**: Comprehensive validation of all configuration values
- **Multiple Environments**: Support for development, production, and custom configurations
- **Reloadable**: Configuration can be reloaded without restarting the application

## Quick Start

### Basic Usage

```python
from openfund_agent.config import ConfigLoader

# Load configuration
loader = ConfigLoader(env="development")
config = loader.load()

# Access configuration
print(config.exchange.name)
print(config.claude.model_version)
print(config.evolution.max_iterations)
```

### Environment Variables

Set required environment variables before loading configuration:

```bash
export EXCHANGE_API_KEY='your_api_key'
export EXCHANGE_API_SECRET='your_api_secret'
export EXCHANGE_API_PASSWORD='your_password'  # For OKX
export CLAUDE_API_KEY='your_claude_api_key'
export FEISHU_WEBHOOK_URL='your_webhook_url'  # Optional
```

### Configuration File Format

Configuration files are in YAML format and support environment variable substitution:

```yaml
exchange:
  name: "okx"
  api_key: "${EXCHANGE_API_KEY}"
  api_secret: "${EXCHANGE_API_SECRET}"
  api_password: "${EXCHANGE_API_PASSWORD}"
  testnet: true
  timeout: 30000

claude:
  api_key: "${CLAUDE_API_KEY}"
  model_version: "claude-3-5-sonnet-20241022"
  max_tokens: 4096
  temperature: 0.7

# ... more configuration sections
```

## Configuration Sections

### 1. Exchange Configuration (`ExchangeConfig`)

Exchange API credentials and connection settings.

```python
config.exchange.name           # Exchange name (okx, binance, bybit)
config.exchange.api_key        # API key
config.exchange.api_secret     # API secret
config.exchange.api_password   # API password (for OKX)
config.exchange.testnet        # Use testnet (True/False)
config.exchange.timeout        # Request timeout in milliseconds
```

### 2. Claude Configuration (`ClaudeConfig`)

Claude API settings for AI decision-making.

```python
config.claude.api_key          # Claude API key
config.claude.model_version    # Model version
config.claude.max_tokens       # Maximum tokens per request
config.claude.temperature      # Temperature (0.0-1.0)
```

### 3. Data Collection Configuration (`DataCollectionConfig`)

Settings for market data collection.

```python
config.data_collection.cache_ttl_minutes        # Cache TTL in minutes
config.data_collection.retry_max_attempts       # Max retry attempts
config.data_collection.retry_delay_seconds      # Retry delay
config.data_collection.supported_timeframes     # List of timeframes
config.data_collection.default_limit            # Default data limit
```

### 4. Strategy Configuration (`StrategyConfig`)

Strategy execution parameters.

```python
config.strategy.default_strategy           # Default strategy name
config.strategy.execution_timeout          # Execution timeout in seconds
config.strategy.max_concurrent_strategies  # Max concurrent strategies
```

### 5. Performance Configuration (`PerformanceConfig`)

Performance analysis settings.

```python
config.performance.analysis_period          # Analysis period (daily/weekly/monthly)
config.performance.min_trades_for_analysis  # Minimum trades for analysis
config.performance.risk_free_rate           # Risk-free rate for calculations
```

### 6. Risk Configuration (`RiskConfig`)

Risk control thresholds and limits.

```python
config.risk.max_iteration_per_day                      # Max iterations per day
config.risk.max_drawdown_threshold                     # Max drawdown (0.0-1.0)
config.risk.min_win_rate_threshold                     # Min win rate (0.0-1.0)
config.risk.core_logic_review_required                 # Require review for core changes
config.risk.backtest_performance_decline_threshold     # Backtest decline threshold
config.risk.live_loss_threshold                        # Live loss threshold
```

### 7. Validation Configuration (`ValidationConfig`)

Code validation and testing settings.

```python
config.validation.docker_image          # Docker image for sandbox
config.validation.docker_timeout        # Docker timeout in seconds
config.validation.run_pytest            # Run pytest tests
config.validation.run_black_check       # Run black formatter check
config.validation.run_backtest          # Run backtest validation
config.validation.backtest_data_days    # Days of data for backtest
```

### 8. Git Configuration (`GitConfig`)

Version control settings.

```python
config.git.auto_commit    # Auto-commit changes
config.git.auto_tag       # Auto-tag versions
config.git.tag_prefix     # Tag prefix (e.g., "agent-v")
```

### 9. Notification Configuration (`NotificationConfig`)

Notification service settings.

```python
config.notification.enabled                      # Enable notifications
config.notification.feishu_webhook               # Feishu webhook URL
config.notification.notify_on_risk               # Notify on risk events
config.notification.notify_on_iteration_complete # Notify on iteration complete
config.notification.notify_on_error              # Notify on errors
```

### 10. Evolution Configuration (`EvolutionConfig`)

Evolution loop parameters.

```python
config.evolution.max_iterations            # Maximum iterations
config.evolution.goal_metric               # Goal metric (e.g., sharpe_ratio)
config.evolution.goal_threshold            # Goal threshold value
config.evolution.iteration_interval_hours  # Hours between iterations
```

### 11. Database Configuration (`DatabaseConfig`)

Database connection settings.

```python
config.database.type    # Database type (sqlite)
config.database.path    # Database file path
```

### 12. Logging Configuration (`LoggingConfig`)

Logging settings.

```python
config.logging.level              # Log level (DEBUG/INFO/WARNING/ERROR/CRITICAL)
config.logging.format             # Log format (json/text)
config.logging.file_path          # Log file path
config.logging.max_file_size_mb   # Max log file size in MB
config.logging.backup_count       # Number of backup files
```

## Advanced Usage

### Custom Configuration File

```python
loader = ConfigLoader(config_path="/path/to/custom/config.yaml")
config = loader.load()
```

### Reload Configuration

```python
# Initial load
config = loader.load()

# ... application runs ...

# Reload configuration (e.g., after file changes)
config = loader.reload()
```

### Error Handling

```python
from openfund_agent.config import ConfigLoader, ConfigLoadError, ConfigValidationError

try:
    loader = ConfigLoader(env="production")
    config = loader.load()
except ConfigLoadError as e:
    print(f"Failed to load configuration: {e}")
except ConfigValidationError as e:
    print(f"Configuration validation failed: {e}")
```

## Validation Rules

The configuration loader validates:

1. **Required Fields**: All required fields must be present
2. **Value Ranges**: Numeric values must be within valid ranges
3. **Positive Values**: Counts and timeouts must be positive
4. **Enum Values**: String values must match allowed options
5. **Environment Variables**: Required environment variables must be set

## Environment Variable Substitution

The loader supports flexible environment variable substitution:

### Simple Substitution
```yaml
api_key: "${EXCHANGE_API_KEY}"
```

### Partial Substitution
```yaml
database_path: "data/${DB_NAME}.db"
```

### List Substitution
```yaml
timeframes:
  - "${TIMEFRAME_1}"
  - "${TIMEFRAME_2}"
  - "1h"
```

### Nested Substitution
```yaml
notification:
  webhook: "${WEBHOOK_URL}"
```

## Configuration Files

Default configuration files are located in the `config/` directory:

- `config/development.yaml` - Development environment
- `config/production.yaml` - Production environment

## Examples

See the `examples/` directory for usage examples:

- `config_loader_demo.py` - Basic configuration loading
- `config_integration_example.py` - Module integration examples

## Testing

Run the test suite:

```bash
pytest tests/test_config_loader.py -v
```

## Best Practices

1. **Never commit credentials**: Use environment variables for sensitive data
2. **Validate early**: Load and validate configuration at application startup
3. **Use type hints**: Leverage the type-safe configuration objects
4. **Environment-specific configs**: Maintain separate configs for dev/prod
5. **Document changes**: Update configuration files with comments

## Troubleshooting

### Configuration validation failed: environment variable not set

**Solution**: Set the required environment variables before running the application.

```bash
export EXCHANGE_API_KEY='your_key'
export EXCHANGE_API_SECRET='your_secret'
export CLAUDE_API_KEY='your_claude_key'
```

### Configuration file not found

**Solution**: Ensure the configuration file exists at the expected path, or specify a custom path:

```python
loader = ConfigLoader(config_path="/path/to/config.yaml")
```

### Invalid YAML syntax

**Solution**: Validate your YAML file syntax. Common issues:
- Incorrect indentation
- Missing colons
- Unquoted special characters

## License

Part of the Openfund Agent project.
