# Bitcoin Trading Bot

A modular, extensible cryptocurrency trading bot with Kraken exchange integration. Built with Python using async/await for high-performance trading.

## Features

- **Kraken Exchange Integration**: Full API support for spot trading
- **Modular Architecture**: Easy to add new exchanges, strategies, and components
- **Multiple Operating Modes**:
  - `dry_run`: Paper trading (no real trades)
  - `live`: Real trading with actual funds
  - `watch`: Monitor market without trading
- **Built-in Strategy**: Simple Moving Average Crossover
- **SQLite Persistence**: Trade history, signals, and execution logs
- **Configurable**: JSON config + environment variables

## Project Structure

```
bitcoin-trading-bot/
├── bot/                    # Core bot orchestration
│   ├── core.py            # Main bot loop
│   └── main.py            # CLI entry point
├── adapter/               # Exchange adapters
│   ├── interface.py       # Abstract adapter interface
│   ├── kraken.py          # Kraken implementation
│   └── factory.py         # Adapter factory
├── strategy/              # Trading strategies
│   ├── interface.py       # Strategy interface
│   ├── ma_crossover.py    # MA crossover strategy
│   └── factory.py         # Strategy factory
├── persistence/           # Database layer
│   └── models.py          # SQLite models
├── configuration/         # Config management
│   ├── config.py          # Config loader
│   └── schema.json        # JSON schema
├── enums/                 # Type-safe enums
├── util/                  # Utilities
├── exceptions.py          # Custom exceptions
├── config.json            # Configuration file
├── .env.example           # Environment template
└── requirements.txt       # Dependencies
```

## Quick Start

### 1. Install Dependencies

```bash
cd bitcoin-trading-bot
pip install -r requirements.txt
```

### 2. Configure the Bot

Copy the example environment file and fill in your credentials:

```bash
cp .env.example .env
```

Edit `.env` or `config.json`:

```json
{
  "core": {
    "mode": "dry_run",
    "interval": 60
  },
  "exchange": {
    "name": "kraken",
    "api_key": "your_kraken_api_key",
    "api_secret": "your_kraken_api_secret",
    "sandbox": true
  },
  "trading": {
    "symbol": "XBT/USD",
    "stake_amount": 100
  },
  "strategy": {
    "name": "simple_ma_crossover",
    "params": {
      "fast_period": 10,
      "slow_period": 30
    }
  }
}
```

### 3. Run the Bot

**Dry-run mode (recommended for testing):**

```bash
python -m bot.main --dry-run
```

**Live trading (use with caution!):**

```bash
python -m bot.main --config config.json
```

**Verbose logging:**

```bash
python -m bot.main --verbose
```

## Kraken API Setup

1. Create a Kraken account: https://www.kraken.com
2. Generate API key: https://www.kraken.com/api/keygen
3. Set permissions:
   - Query funds (for balance checks)
   - Trade (for order execution)
   - Query open orders (for order management)
4. **Important**: IP whitelist your server for security

## Configuration Options

### Core Settings

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `mode` | string | `dry_run` | Operating mode: dry_run, live, watch |
| `interval` | int | 60 | Loop interval in seconds |
| `max_retries` | int | 3 | Max retry attempts on failure |
| `retry_delay` | int | 5 | Delay between retries (seconds) |

### Exchange Settings

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `name` | string | `kraken` | Exchange name |
| `api_key` | string | - | API key (required for live) |
| `api_secret` | string | - | API secret (required for live) |
| `sandbox` | bool | true | Use sandbox/test mode |

### Trading Settings

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `symbol` | string | `XBT/USD` | Trading pair |
| `stake_amount` | float | 100 | Amount per trade (USD) |
| `max_daily_trades` | int | 10 | Max trades per day |
| `stop_loss` | float | null | Stop loss % (e.g., 5.0) |
| `take_profit` | float | null | Take profit % (e.g., 10.0) |

### Strategy Settings (MA Crossover)

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `fast_period` | int | 10 | Fast MA period |
| `slow_period` | int | 30 | Slow MA period |
| `ma_type` | string | `sma` | MA type: sma, ema, wma |
| `min_confidence` | float | 0.5 | Min confidence to trade |

## Adding Custom Strategies

Create a new strategy file in `strategy/`:

```python
# strategy/my_strategy.py
from .interface import Strategy, TradingDecision
from enums import Signal

class MyCustomStrategy(Strategy):
    id = "my_custom_strategy"
    name = "My Custom Strategy"
    version = "1.0.0"
    
    async def analyze(self, ohlcv, current_price, context):
        # Your strategy logic here
        decision = TradingDecision(
            signal=Signal.BUY,
            confidence=0.8,
            reason="My analysis"
        )
        return decision
```

Register it in `strategy/factory.py`:

```python
def _register_builtin_strategies(self):
    from .my_strategy import MyCustomStrategy
    self.register_strategy(MyCustomStrategy)
```

## Database Schema

The bot uses SQLite with the following tables:

- **trades**: Trade execution history
- **strategy_signals**: All signals generated by strategies
- **execution_logs**: Bot execution logs and errors
- **bot_state**: Persistent bot state

Query your data:

```bash
sqlite3 trading_bot.db "SELECT * FROM trades LIMIT 10;"
sqlite3 trading_bot.db "SELECT * FROM strategy_signals ORDER BY timestamp DESC LIMIT 10;"
```

## Safety Features

1. **Dry-run mode**: Test strategies without risking real money
2. **Rate limiting**: Respects exchange rate limits
3. **Error handling**: Graceful failure with logging
4. **Config validation**: Catches misconfiguration at startup
5. **Max daily trades**: Prevents overtrading

## Security Best Practices

- ✅ Store API keys in `.env`, not in code
- ✅ Add `.env` to `.gitignore`
- ✅ Use IP whitelisting for API keys
- ✅ Start with dry-run mode
- ✅ Use minimal API permissions
- ✅ Monitor logs regularly

## Development

### Run Tests

```bash
pytest tests/ -v
```

### Add New Exchange

1. Create `adapter/{exchange}.py` implementing `ExchangeAdapter`
2. Register in `adapter/factory.py`
3. Add to supported exchanges in enums

### Architecture

The bot follows a modular architecture:

```
┌─────────────┐     ┌──────────────┐     ┌─────────────┐
│   Bot Core  │────▶│   Adapter    │────▶│  Kraken API │
│  (Loop)     │     │  (Kraken)    │     │             │
└─────────────┘     └──────────────┘     └─────────────┘
       │
       │
       ▼
┌─────────────┐     ┌──────────────┐     ┌─────────────┐
│  Strategy   │◀────│    Data      │◀────│   OHLCV     │
│  (MA Cross) │     │  Provider    │     │   Data      │
└─────────────┘     └──────────────┘     └─────────────┘
       │
       ▼
┌─────────────┐     ┌──────────────┐
│  Database   │◀────│   Results    │
│  (SQLite)   │     │  (Trades)    │
└─────────────┘     └──────────────┘
```

## Troubleshooting

### "Authentication failed"

- Check API key and secret are correct
- Verify API permissions on Kraken
- Ensure IP is whitelisted (if configured)

### "Rate limit exceeded"

- Increase `retry_delay` in config
- Reduce `interval` between loops
- Check Kraken rate limits: https://docs.kraken.com/rest/#rate-limits

### "Symbol not found"

- Kraken uses `XBT/USD` not `BTC/USD`
- Check available pairs: https://www.kraken.com/prices

## License

MIT License - feel free to modify and distribute.

## Disclaimer

**This software is for educational purposes only.** Cryptocurrency trading involves substantial risk of loss. Always test thoroughly in dry-run mode before using real funds. The authors are not responsible for any financial losses.
