Skip to content

Simplify README, implement real Claude API, add tests - #6

Merged
DaScient merged 3 commits into
mainfrom
claude/inspiring-curie-37rrs1
Oct 2, 2026
Merged

DaScient merged 3 commits into
mainfrom
claude/inspiring-curie-37rrs1

Conversation

@DaScient

@DaScient DaScient commented Oct 2, 2026

Copy link
Copy Markdown
Owner

Summary

This PR significantly streamlines the ClaudeTrader documentation and implementation to reflect what actually works today, while adding real Anthropic Claude API integration with a mock fallback, comprehensive test coverage, and bug fixes.

Key Changes

Documentation & Scope

  • Rewrote README.md from aspirational 271 lines to a practical 154-line guide that clearly distinguishes implemented features (✅) from placeholders (⚠️) and unimplemented work (❌)
  • Added a "What works today" status table showing real vs. mock implementations
  • Clarified that market data is synthetic and the REST API is a design spec, not implemented
  • Simplified architecture diagram to match actual codebase structure

Claude LLM Integration (models/llm_interface.py)

  • Real Anthropic API calls via the official anthropic SDK (1.11.0+)
    • Uses the Messages API with beta.messages.create() for extended thinking support
    • Supports Claude effort levels (low, medium, high, xhigh, max) via output_config
    • Implements server-side refusal fallback (fallbacks: "default")
    • Extracts text from extended thinking responses (filters out thinking blocks)
  • Graceful mock fallback when ANTHROPIC_API_KEY is not set or anthropic package is missing
  • Caching of identical prompts for one hour to reduce API calls
  • Refusal handling returns error messages instead of raising exceptions
  • Updated default model to claude-opus-5-5 and max tokens to 16000

Trade Validation & Sizing (integrations/supertrend_bot_integration.py)

  • Strict decision parsing in execute_with_validation(): trades execute only when Claude explicitly answers DECISION: EXECUTE with CONFIDENCE >= threshold
  • Unparseable responses (including mock responses) are treated as rejections (fail-closed)
  • Added _parse_decision() static method using regex to extract decision and confidence from free-form text
  • Position sizing now respects account balance cap and returns units alongside notional value

Engine & Signal Generation (core/engine.py)

  • Added _to_trading_signal() to convert strategy signals to engine TradingSignal objects
  • Automatically computes ATR-based stop-loss and take-profit levels using compute_exit_levels()
  • Fixed strategy config fallback to avoid KeyError when strategies section is missing
  • Updated default LLM config to use claude-opus-5-5 and effort: medium

Backtester Fixes (utils/backtest.py)

  • Fixed handling of missing open field in OHLCV data (falls back to close)
  • Corrected trailing stop logic: only ratchets after a bar closes, preventing the same bar's low from triggering its own stop
  • Improved signal semantics: hold now means "no new signal" (position stays open), not "close position"
  • Better gap handling: stops that gap through fill at the open price

Indicator Robustness (utils/indicators.py)

  • ADX rewrite using Wilder's smoothing (proper +DI, -DI, DX calculation)
    • Returns neutral 25.0 when insufficient data
    • Price-scale independent (tested with 1000x scaling)
    • Bounded 0–100
  • RSI returns neutral 50.0 for series shorter than period
  • ATR handles single-bar and empty series gracefully

Test Coverage

  • test_llm_interface.py (83 lines): mock fallback, API key detection, Anthropic request shape, refusal handling
  • test_engine.py (35 lines): signal generation, ATR exit level computation
  • test_integration.py (35 lines): trade gating decision parsing, position sizing
  • test_indicators.py (33 lines): ADX edge cases, RSI neutrality, ATR single-bar
  • test_backtest.py additions: hold signal semantics, gap fills

https://claude.ai/code/session_015rhcFXLJHUCwo4mn74RAHy

claude added 3 commits October 2, 2026 07:55
LLMInterface now creates a real anthropic.Anthropic client when
ANTHROPIC_API_KEY (or ANTHROPIC_AUTH_TOKEN / config api_key) is set and
falls back to MockLLMClient otherwise, or when use_mock is true.
Default model is claude-opus-5-5 with a configurable effort level and
server-side refusal fallback. Refusals and API errors surface as clear
messages. Adds tests that exercise the request shape without network.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015rhcFXLJHUCwo4mn74RAHy
Backtester:
- "hold" no longer closes positions. SuperTrend emits buy/sell only on
  the flip bar, so every trade was closed after exactly one bar.
- Trailing stop is ratcheted after the exit check, so a bar's close can
  no longer tighten the stop that bar's low is tested against.
- Stops/targets hit by a gap fill at the bar open instead of the level.

Metrics/indicators:
- Sortino downside deviation is averaged over all periods.
- calculate_adx is a real Wilder ADX (was ATR * 0.5, price-scale dependent).
- calculate_atr / calculate_rsi handle series that are too short.

Engine/integration:
- get_signals always returned [] (StrategySignal has no .symbol); strategy
  signals are now converted to TradingSignal with ATR stop/target, and the
  LLM prompt gets a market summary instead of the full OHLCV dump.
- execute_with_validation approved trades from a heuristic score and ignored
  the model's answer; it now parses DECISION/CONFIDENCE and fails closed.
- Position sizing returned notional labelled as size; it now returns
  notional (capped at balance) and units.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015rhcFXLJHUCwo4mn74RAHy
Replace the aspirational architecture (agents/, rag/, nlp/, api/ etc. that
do not exist) with a status table of what is implemented, what is a mock
(market data, RAG) and what is a placeholder (multi-factor, RL, REST API).
Document the Claude configuration and mock fallback, the backtester's fill
and exit rules, and the working `python -m` entry points. Mark
docs/API.md as an unimplemented design spec.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015rhcFXLJHUCwo4mn74RAHy
Copilot AI balanced review requested due to automatic review settings October 2, 2026 08:00
@DaScient
DaScient merged commit 74f2b41 into main Oct 2, 2026
1 check passed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Gap ordering, sequence handling, cache keys, and sizing validation contain unresolved correctness issues.

Review effort: Balanced
Findings: 1 High severity · 2 Medium severity

Open (3)
What changed in this PR

Adds real Anthropic integration, improves trading calculations and backtesting behavior, aligns documentation with implemented functionality, and expands tests.

Changes:

  • Implements Anthropic API calls, caching, trade gating, and position sizing.
  • Improves indicators, signal conversion, backtest exits, and performance metrics.
  • Rewrites documentation and adds comprehensive tests.
File Description
ClaudeTrader/​README.md Documents current capabilities and limitations.
ClaudeTrader/​configs/​default_config.yaml Adds current Anthropic options.
ClaudeTrader/​core/​engine.py Converts strategy signals and computes exits.
ClaudeTrader/​docs/​API.md Marks the API as unimplemented.
ClaudeTrader/​docs/​README.md Updates documentation links and scope.
ClaudeTrader/​integrations/​supertrend_bot_integration.py Adds strict trade gating and sizing.
ClaudeTrader/​models/​llm_interface.py Implements Anthropic requests and fallback behavior.
ClaudeTrader/​requirements.txt Enables the Anthropic dependency.
ClaudeTrader/​setup.py Updates the optional Anthropic dependency.
ClaudeTrader/​tests/​test_backtest.py Tests hold, gap, and trailing-stop behavior.
ClaudeTrader/​tests/​test_engine.py Tests signal conversion and exit levels.
ClaudeTrader/​tests/​test_indicators.py Tests indicator edge cases.
ClaudeTrader/​tests/​test_integration.py Tests gating and sizing.
ClaudeTrader/​tests/​test_llm_interface.py Tests LLM requests and fallback behavior.
ClaudeTrader/​tests/​test_performance.py Tests Sortino downside deviation.
ClaudeTrader/​utils/​backtest.py Revises signal and gap execution semantics.
ClaudeTrader/​utils/​indicators.py Improves RSI, ATR, and ADX behavior.
ClaudeTrader/​utils/​performance.py Corrects Sortino downside deviation.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +156 to +157
has_open = bool(ohlcv.get("open"))
open_ = [float(x) for x in ohlcv["open"]] if has_open else list(close)
Comment on lines +176 to +179
risk_amount = account_balance * risk_per_trade
stop_loss_pct = signal.get('stop_loss_pct', 0.02)
position_size = risk_amount / stop_loss_pct
notional = min(risk_amount / stop_loss_pct, account_balance) if stop_loss_pct > 0 else 0.0
price = signal.get('price')
) -> str:
"""Generate cache key for a prompt"""
cache_input = f"{prompt}|{system_prompt}|{temperature}|{self.model}"
cache_input = f"{prompt}|{system_prompt}|{temperature}|{self.model}|{self.effort}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants