# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

**Brighter Trading** - Cryptocurrency trading platform with Blockly-based strategy builder

## ⚠️ CRITICAL: Updating Todos, Milestones, and Goals

**DO NOT edit `todos.md`, `milestones.md`, or `goals.md` files directly.**

These files are managed by Development Hub which has file watchers and sync logic. Direct edits will be overwritten or cause conflicts.

**Use the `devhub-tasks` CLI instead:**

```bash
# Status overview
devhub-tasks status brightertrading

# Add todos
devhub-tasks todo add brightertrading "Task description" --priority high --milestone M1

# Complete todos (by text match or ID number)
devhub-tasks todo complete brightertrading "Task description"
devhub-tasks todo complete brightertrading 3

# List todos
devhub-tasks todo list brightertrading

# Add milestones
devhub-tasks milestone add brightertrading M2 --name "Milestone Name" --target "March 2026"

# Complete milestones (also completes linked todos)
devhub-tasks milestone complete brightertrading M1

# Goals
devhub-tasks goal add brightertrading "Goal description" --priority high
devhub-tasks goal complete brightertrading "Goal description"
```

Use `--json` flag for machine-readable output. Run `devhub-tasks --help` for full documentation.

**Files you CAN edit directly:** `overview.md`, `architecture.md`, `README.md`, and any other docs.

## Development Commands

```bash
# Install for development
pip install -e ".[dev]"

# Run tests
pytest

# Run a single test
pytest tests/test_file.py::test_name
```

## Architecture

Flask web application with SocketIO for real-time communication, using eventlet for async operations. Features a Blockly-based visual strategy builder frontend with a **unified broker abstraction** supporting backtest, paper, and live trading modes.

```
┌─────────────────────────────────────────────────────────────────┐
│                        Flask + SocketIO                         │
│                          (app.py)                               │
├─────────────────────────────────────────────────────────────────┤
│                      BrighterTrades                             │
│              (Main application facade/coordinator)              │
├─────────┬─────────┬─────────┬─────────┬─────────┬──────────────┤
│  Users  │Strategies│ Trades │Indicators│Backtester│ Exchanges   │
├─────────┴─────────┴─────────┴─────────┴─────────┴──────────────┤
│                      Broker Abstraction                         │
│        (BaseBroker → Paper / Backtest / Live brokers)          │
├─────────────────────────────────────────────────────────────────┤
│                         DataCache                               │
│               (In-memory caching + SQLite)                      │
└─────────────────────────────────────────────────────────────────┘
```

### Key Modules

| Module | Purpose |
|--------|---------|
| `app.py` | Flask web server, SocketIO handlers, HTTP routes |
| `BrighterTrades.py` | Main application facade, coordinates all subsystems |
| `Strategies.py` | Strategy CRUD operations and execution management |
| `StrategyInstance.py` | Base strategy execution context |
| `paper_strategy_instance.py` | Paper trading strategy instance |
| `backtest_strategy_instance.py` | Backtest strategy instance |
| `live_strategy_instance.py` | Live trading strategy instance with circuit breaker and position limits |
| `PythonGenerator.py` | Generates Python code from Blockly JSON |
| `backtesting.py` | Strategy backtesting engine (uses backtrader) |
| `indicators.py` | Technical indicator calculations |
| `candles.py` | Candlestick/OHLCV data management |
| `trade.py` | Trade lifecycle management |
| `ExchangeInterface.py` | Multi-exchange interface |
| `Exchange.py` | Single exchange wrapper (uses ccxt) |
| `DataCache_v3.py` | In-memory caching with database persistence |
| `Database.py` | SQLite database operations |
| `Users.py` | User authentication and session management |
| `Signals.py` | Trading signal definitions and state tracking |
| `ExternalSources.py` | Real-time external API data for live strategies |
| `ExternalIndicators.py` | Historical external API data for backtesting |
| `health.py` | Application health checks |
| `logging_config.py` | Centralized logging configuration |
| `Configuration.py` | Settings management with YAML persistence |
| `backtest_result.py` | Backtest result schema (dataclasses) |
| `mapped_strategy.py` | Backtrader strategy integration |
| `shared_utilities.py` | Time/date conversion utilities |
| `utils.py` | JSON serialization helpers |
| `exchange_validation.py` | Exchange requirements validation with structured error codes |

### EDM Client Module (`src/edm_client/`)

| Module | Purpose |
|--------|---------|
| `client.py` | REST client for Exchange Data Manager service |
| `websocket_client.py` | WebSocket client for real-time candle data |
| `models.py` | Data models (Candle, Subscription, EdmConfig) |
| `exceptions.py` | EDM-specific exceptions |

### Broker Module (`src/brokers/`)

| Module | Purpose |
|--------|---------|
| `base_broker.py` | Abstract broker interface (BaseBroker) |
| `paper_broker.py` | Simulated trading with virtual balance |
| `backtest_broker.py` | Historical data backtesting |
| `live_broker.py` | Real exchange trading via ccxt |
| `factory.py` | Creates appropriate broker based on mode |

### Wallet Module (`src/wallet/`)

Bitcoin wallet system for strategy fees with two-address custody model.

| Module | Purpose |
|--------|---------|
| `wallet_manager.py` | Main wallet operations, credits ledger, fee accumulation/settlement |
| `bitcoin_service.py` | Bitcoin key generation, transaction creation, address validation |
| `encryption.py` | Versioned key encryption for stored private keys |
| `background_jobs.py` | Deposit detection, withdrawal processing, auto-sweep jobs |

**Key concepts:**
- **Fee Address**: Platform-controlled address for strategy fees (private key stored encrypted)
- **Sweep Address**: User-controlled address for excess funds (we only store public address)
- **Credits Ledger**: Internal balance for instant, reliable strategy fee deduction
- **Balance Cap**: ~$50 limit before auto-sweep to user's sweep address

### Key Paths

- **Source code**: `src/`
- **Tests**: `tests/`
- **Configuration**: `config.yml`
- **Database**: `BrighterTrading.db` (SQLite)
- **Documentation**: `docs/` (symlink to project-docs)

### Running the Application

```bash
# Start the development server
cd src && python app.py

# Or from project root
python src/app.py
```

The application runs on `http://127.0.0.1:5002` by default.

## Documentation

Documentation lives in `docs/` (symlink to centralized docs system).

**Before updating docs, read `docs/updating-documentation.md`** for full details on visibility rules and procedures.

Quick reference:
- Edit files in `docs/` folder
- Use `public: true` frontmatter for public-facing docs
- Use `<!-- PRIVATE_START -->` / `<!-- PRIVATE_END -->` to hide sections
- Deploy: `~/PycharmProjects/project-docs/scripts/build-public-docs.sh brightertrading --deploy`

Do NOT create documentation files directly in this repository.
