Skip to content

Latest commit

 

History

History
339 lines (242 loc) · 11 KB

File metadata and controls

339 lines (242 loc) · 11 KB

CLAUDE.md

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

Commands

# Run the bot
python -m src.main

# Install dependencies
pip install -r requirements.txt

# Run tests
python3 -m pytest tests/ -v

# Deploy to server (from repo root)
sudo ./scripts/update.sh

Testing Requirements

CRITICAL: All tests must pass. Always. No exceptions.

  1. Run the full test suite: python3 -m pytest tests/ -v
  2. If any test fails, fix it immediately before proceeding
  3. Never create a PR with failing tests
  4. Never ignore failing tests - they indicate real bugs that must be fixed
  5. If your changes break existing tests, fix the tests or fix your code

The 12 Coinbase integration test "errors" are expected - they refuse to run without test credentials (security feature). These are not failures.

Architecture

Trading Bot supporting Coinbase and Kraken exchanges with multi-indicator confluence strategy.

Core Flow

src/main.pysrc/daemon/runner.py (main loop) → Exchange client + Strategy + Safety systems

Exchange Abstraction

All exchange clients implement ExchangeClient protocol (src/api/exchange_protocol.py):

  • coinbase_client.py, kraken_client.py, paper_client.py
  • Factory pattern in exchange_factory.py selects client based on config
  • Trading pairs normalized to BASE-QUOTE format (e.g., BTC-USD)

Safety Systems (all in src/safety/)

  • KillSwitch: File-based or signal-based halt, requires manual reset
  • CircuitBreaker: Multi-level (GREEN→YELLOW→RED→BLACK) with auto-cooldown
  • LossLimiter: Daily/hourly loss limits with progressive throttling
  • Validator: Aggregates all safety checks, provides position multiplier

Strategy

src/strategy/signal_scorer.py combines RSI, MACD, Bollinger, EMA, Volume into -100 to +100 score. Trade when |score| ≥ threshold.

Database Operations

All database operations MUST support both PAPER and ACTUAL (live) trading modes. They MUST be kept completely separate:

  • Every table with trading data has is_paper column
  • All queries MUST filter by is_paper parameter
  • Paper and live data must NEVER mix
  • Both modes must be independently functional
  • Test with paper trading before enabling live trading

Schema Migrations

This project uses Base.metadata.create_all() instead of Alembic for simplicity:

  • New tables: Automatically created on startup - no migration needed
  • Schema changes to existing tables: Use _run_migrations() in database.py
  • SQLite handles this well: create_all() is idempotent (creates missing tables, skips existing)

Do NOT suggest Alembic migrations for new tables - they are unnecessary in this codebase.

Versioning & Commits

This project uses Conventional Commits for automatic semantic versioning.

Commit Message Format

<type>(<scope>): <description>

[optional body]

[optional footer]

Commit Types

Type Version Bump Description
feat MINOR New feature
fix PATCH Bug fix
perf PATCH Performance improvement
refactor PATCH Code refactoring
docs none Documentation only
style none Formatting, no code change
test none Adding/updating tests
chore none Maintenance tasks
ci none CI/CD changes
build none Build system changes

Breaking Changes

Add ! after type or include BREAKING CHANGE: in footer for MAJOR version bump:

feat!: remove deprecated API endpoint

Examples

feat(strategy): add momentum indicator
fix(api): handle rate limit errors
perf(db): optimize trade query
docs: update README setup instructions
chore(deps): update pandas to 2.0

Automatic Version Bumps

Do NOT manually edit src/version.py.

Versions are automatically bumped when PRs merge to main based on commit types.

Configuration Parameters

When creating new configuration parameters:

  1. Add the field to config/settings.py with proper Field validation
  2. MUST update .env.example with the recommended default and documentation
  3. Use descriptive comments explaining the parameter's purpose and valid range

Branching

  • main: Production branch (deployed to server)
  • develop: Development/integration branch
  • feature/*: Feature branches (e.g., feature/add-stop-loss)
  • fix/*: Bug fix branches (e.g., fix/telegram-timeout)

Workflow

  1. Create feature/fix branch from develop
  2. Make changes and commit using conventional commit format
  3. Push and create PR to develop
  4. After review, merge to develop
  5. When ready for release, create PR from develop to main

Creating PRs to Main

Before creating a PR from develop to main:

git fetch origin main
git rebase origin/main           # Ensure develop is up-to-date with main
git push --force-with-lease      # Update remote develop
git log origin/main..develop --oneline  # See actual new commits

This ensures the PR only shows commits that are actually new.

Rules

  • All merges to main must be done via pull requests
  • Direct commits to main are not allowed
  • NEVER delete the develop branch - feature branches depend on it. Do NOT use --delete-branch when merging PRs from develop to main.
  • ALWAYS check that a PR is still OPEN before pushing commits to it - use gh pr view {NUMBER} --json state

Pull Request Reviews (CRITICAL)

This is a FINANCIAL TRADING SYSTEM. All PR review comments MUST be fetched and thoroughly analyzed before merging.

Issue Priority for Financial Systems

Priority Symbol Action Required
Critical 🔴 MUST fix before merge - blocks deployment
High 🟡 MUST fix before merge - financial system requirement
Low 🟢 Fix if straightforward, otherwise document and create issue

Both 🔴 Critical AND 🟡 High priority issues trigger automatic fix workflows.

Fetching PR Review Comments

# Get all comments on a PR (includes bot reviews)
gh api repos/Byte-Ventures/claude-trader/issues/{PR_NUMBER}/comments

# Get code review comments (inline)
gh api repos/Byte-Ventures/claude-trader/pulls/{PR_NUMBER}/comments

# View PR with all details
gh pr view {PR_NUMBER} --comments

Updating PRs

Use gh api instead of gh pr edit to avoid GitHub Projects Classic deprecation errors:

# Update PR title
gh api repos/Byte-Ventures/claude-trader/pulls/{PR_NUMBER} -X PATCH -f title="new title"

# Update PR body
gh api repos/Byte-Ventures/claude-trader/pulls/{PR_NUMBER} -X PATCH -f body="new body"

# Get PR info
gh api repos/Byte-Ventures/claude-trader/pulls/{PR_NUMBER} --jq '.title, .state'

Review Process

  1. Critical issues (🔴) - MUST fix before merge
  2. High priority issues (🟡) - MUST fix before merge (financial system)
  3. Low priority issues (🟢) - Fix if straightforward, or create GitHub issue
  4. Security concerns require immediate attention
  5. After fixes, push new commit and re-request review if needed

Bot Reviews

The claude[bot] automatically reviews PRs. Its comments appear under /issues/{PR_NUMBER}/comments. Always read these thoroughly - they may identify:

  • Type errors
  • Security vulnerabilities
  • Missing error handling
  • API compatibility issues

Handling Identified Issues

All issues identified in PR reviews MUST be handled. Do NOT ignore or dismiss issues.

This is a financial trading system. Every identified issue could affect money or data integrity. Ignoring issues is unacceptable.

First, verify the issue - Check if the issue actually exists in the code (bot reviews can be wrong).

Then, do ONE of the following:

  1. Fix it - Commit a fix addressing the issue
  2. Document why it's not an issue - Add a code comment explaining why the concern doesn't apply
  3. Defer to GitHub issue - Create a GitHub issue to track the fix for a future PR (use gh issue create)
  4. Explicitly decline - Document in PR comments why the suggestion won't be implemented

No issue should be left unacknowledged. When summarizing PR reviews, create a checklist showing how each issue was handled.

Priority levels:

  • 🔴 Critical - MUST fix before merge
  • 🟡 High/Medium - MUST fix before merge (financial system requirement)
  • 🟢 Low - Fix if straightforward, otherwise create GitHub issue

Deferred Issues MUST Become GitHub Issues

Any PR review issue that is not fixed in the current PR MUST have a GitHub issue created.

This ensures:

  • Nothing falls through the cracks
  • Issues are tracked and searchable
  • Future work is documented with full context

When creating issues for deferred PR review items:

gh issue create --title "Brief description" --body "## Summary
...
## Context
From PR #XX review (bot review, YYYY-MM-DD)
## Priority
Low/Medium/High"

Code Change Guidelines

When making changes to this codebase:

  1. Read first, code second - Understand the codebase before making changes
  2. Verify, don't invent - Check that APIs/methods exist before using them
  3. Minimal changes - Fix only what's needed, don't refactor or "improve"
  4. Follow patterns - Check similar files for existing conventions
  5. No new dependencies - Unless the issue explicitly requires them
  6. Stay focused - Don't modify unrelated code
  7. Test both modes - Run tests that cover paper and live trading
  8. Note uncertainties - If the issue is ambiguous, document assumptions in PR

Protected Paths (extra caution required)

These paths affect money and safety - changes require extra verification:

  • src/safety/ - Circuit breaker, kill switch, loss limiter
  • src/api/*_client.py - Exchange integration (order execution)
  • config/settings.py - Core configuration

Automation Workflows

Required GitHub Labels

These labels must exist for automation to work:

Label Purpose
auto-fix Triggers automatic issue fixing via Claude
fix-in-progress Applied when auto-fix is working on an issue
post-mortem Marks issues derived from post-mortem analysis
review-retry-N Created automatically (N=1,2,3) to track fix attempts

Required Discussion Category

Create a post-mortems discussion category with:

  • Format: Announcement (restricts creation to maintainers)
  • Purpose: Post-mortem analysis from tools/postmortem.py

Workflow Chain

Post-mortem discussion created
        ↓
claude-postmortem-review.yml analyzes fixes
        ↓
Issue created with 'auto-fix' label
        ↓
claude-auto-fix.yml implements fix
        ↓
PR created to develop
        ↓
claude[bot] reviews PR
        ↓
If 🔴 critical OR 🟡 high priority issues:
  claude-address-review.yml fixes them (max 3 retries)
        ↓
Human reviews and merges PR
        ↓
close-linked-issues.yml closes referenced issues
        ↓
semantic-release.yml bumps version on main

Manual Triggering

To manually trigger auto-fix on any issue:

  1. Ensure you have write access to the repo
  2. Add the auto-fix label to the issue
  3. Monitor the Actions tab for progress