AI Strategy (KlawTrade AI)
KlawTrade AI is the optional LLM-powered signal generator that ships inside the same binary as the classic rule-based bot. You bring your own Anthropic or OpenAI API key; KlawTrade handles prompting, structured output, validation, and pipeline integration.
The core promise: accuracy is preserved. Every signal the LLM emits is piped through the same 14-check deterministic risk gate as rule-based signals, and is additionally cross-validated against classic indicators before it can even reach that gate.
How accuracy is preserved
- Strict JSON schema -- Claude uses tool_use and OpenAI uses response_format=json_schema, so the model is forced to emit a structured decision with
action,confidence, stop loss, take profit, and confirming indicators. - Temperature = 0 by default -- deterministic output. Same prompt, same reply.
- Confidence threshold -- signals below
min_confidence(default 0.75, stricter than rule strategies) are discarded. - Rule cross-validation -- every BUY/SELL must agree with at least one classic indicator (RSI, MACD, SMA cross, Bollinger). Hallucinated trades are filtered out before they reach the risk manager.
- Stop/take sanity checks -- stops on the wrong side of the entry price are nulled so the risk manager can compute a safe default.
- 14-check risk gate -- the same absolute gate used by the rule strategies. The LLM cannot override position sizing, drawdown limits, daily loss caps, or any other check.
- Hard spend cap --
max_daily_cost_usdpauses the strategy once the day's LLM spend is reached. A per-symbol cache coalesces calls to keep usage low.
Supported providers
Anthropic (Claude)
- Default provider; uses tool_use for structured output.
- Recommended model:
claude-sonnet-4-20250514. - API key from
ANTHROPIC_API_KEYenv var orstrategy.ai.api_keyin config.
OpenAI (GPT)
- Uses structured-outputs (
response_format) to enforce the same JSON schema. - Recommended models:
gpt-4o-mini(cheap) orgpt-4.1(accurate). - API key from
OPENAI_API_KEYenv var orstrategy.ai.api_keyin config.
Quick start
Install with the AI extras, export your key, flip the flag in config/settings.yaml, and start the bot as usual.
# 1. Install with AI dependencies pip install "klawtrade[ai]" # 2. Export your key (pick one) export ANTHROPIC_API_KEY="sk-ant-..." # or export OPENAI_API_KEY="sk-..." # 3. Enable the AI strategy in config/settings.yaml # strategy: # ai: # enabled: true # provider: "anthropic" # min_confidence: 0.75 # 4. Run — same CLI as the classic bot klawtrade start
Configuration
All settings live under strategy.ai in config/settings.yaml:
strategy:
ai:
enabled: true
provider: "anthropic" # or "openai"
api_key: "" # blank = read from env
model: "" # blank = provider default
temperature: 0.0 # 0 = deterministic
max_tokens: 1024
timeout_seconds: 30
min_confidence: 0.75 # stricter than rules
require_rule_confirmation: true # cross-validate signals
max_daily_cost_usd: 10.00 # hard spend cap
cache_ttl_seconds: 60 # coalesce per-symbol calls
rules:
momentum: true
mean_reversion: trueRunning AI-only
Set both rules.momentum and rules.mean_reversion to false with ai.enabled: true. The engine will refuse to start with zero active strategies.
Decision schema
The LLM must return a JSON object matching this exact shape. Both providers enforce this at the API level, so invalid JSON is impossible by construction:
{
"action": "BUY" | "SELL" | "CLOSE" | "HOLD",
"confidence": 0.0 - 1.0,
"reasoning": "2-3 sentences citing specific indicators",
"confirming_indicators": ["macd_bullish", "above_sma200", ...],
"stop_loss_price": number | null,
"take_profit_price": number | null
}Same brokers, same dashboard
KlawTrade AI reuses every existing plugin — the six broker integrations (Alpaca, Interactive Brokers, Coinbase, Binance, Kraken, Tradier), the backtest engine, the real-time dashboard, the SQLite audit log, and the circuit breaker. Only the signal generator changes.
Cost control
- Per-symbol cache -- a TTL window (default 60s) coalesces concurrent snapshots into one API call per symbol.
- Daily cost cap -- the strategy pauses automatically once
max_daily_cost_usdis reached. - Model choice -- use
claude-3-5-haikuorgpt-4o-minifor roughly 10x lower cost per decision.
AI vs rule-based: which one?
Both bots share the same risk gate, so neither can blow up the account. The difference is signal source:
- Rule-based-- reproducible, zero inference cost, easy to backtest, but can miss regime shifts that aren't encoded in the indicators.
- AI-powered -- can weigh multiple indicators together and express uncertainty with a calibrated confidence score, at the cost of inference latency and API spend.
- Both together -- run all three strategies simultaneously; the risk manager arbitrates across them and you get a de-facto ensemble.