trading_database.py:
- migrate_from_json: validate exit_time > entry_time before applying exit update
Trades with exit before entry are logged as open (no invalid exit applied)
This prevents the timestamp inversion bug that corrupted the DB with 625 bad trades
position_monitor.py:
- Replace fragile datetime.strptime('%Y-%m-%d %H:%M:%S') with fromisoformat()
Handles both space-separated and ISO 8601 T-separated formats, strips microseconds
trading_bot_gui.py:
- Call infra.log_bot_status('running') on bot start -> bot_status table now populated
- Call infra.log_bot_status('stopped') on bot stop
Previously bot_status table remained empty (0 rows), making monitoring impossible
telegram_bot_commands_old.py:
- Remove superseded file (replaced by telegram_bot_commands.py)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
enhanced_trailing_stop.py:
- mt -> mt5 (all occurrences)
- Add pandas + timezone imports at file top
- Fix UTC bug: datetime.fromtimestamp(..., tz=timezone.utc).replace(tzinfo=None)
- Fetch symbol_info once per call, reuse for point (was called twice)
- cleanup_closed_positions: handle None from positions_get()
- Remove pandas import from inside function body
dynamic_threshold_optimizer.py:
- Fix SQL injection: replace f-string session filter with parameterized query (?)
- Add logging module, replace all print() with logger calls
- Use context manager (with sqlite3.connect()) to prevent connection leak on exception
- save_thresholds_to_config: add try/except with logger.error
signal_cache.py:
- Fix bare except -> except Exception in _cleanup_old_entries
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
equity_curve_trading.py:
- mt→mt5 alias in _get_current_equity()
- safe-fail: return False (block trade) when equity unavailable
- UTC timestamps via timezone.utc in update_equity()
- add_initial_equity(): unique timestamps (staggered by minute) instead of identical
infrastructure_patch.py:
- Add logging module, replace all print() with logger calls
- Fix guard: self.db/self.telegram instead of enable_database/enable_telegram
- Fix UTC bug in extract_trade_data_from_mt5() (fromtimestamp with tz=utc)
- Remove direct self.db.cursor.execute() in log_trade_exit() — use get_open_trades()
- Read risk_pct from SESSION_WHITELIST_CONFIG instead of hardcoding 0.01
news_filter.py / news_filter_v2.py:
- Remove both inactive variants (ForexFactory scraper + Finnhub API)
- news_filter_simple.py + news_filter_integration.py remain as active implementation
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Replace pytz.UTC with timezone.utc in AdaptiveRhythmManager
class definition (cell 8) and debug session cell (cell 106).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add signal_cache.py module to persist signal data between trade open/close
- Modify execute_trade_v2_adaptive to cache signal info when trade opens
- Update sync_closed_trades_to_tracker to retrieve cached ML features
- Update scheduled_demo_tracker_sync with same ML feature retrieval
This enables proper ML training by capturing:
- base_confidence, enhanced_score, hybrid_score
- signal_quality, market_regime, regime_strength
- session and lot_multiplier
Previously all trades were logged with 0 values for ML features.
After ~50-100 new trades, the ML model can be properly trained.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- New ml_signal_predictor.py with XGBoost model
- Feature extraction from historical trades (17 features)
- 5-fold cross-validation for robust training
- Integrated into enhanced_trading_check_wrapper as optional layer
- Disabled by default until model improves (AUC: 0.508)
- Key insight: Asian session is strongest predictor of success
Features used:
- Signal: confidence, threshold, regime_strength
- Session: asian/london/ny/overlap (one-hot)
- Time: hour (cyclical), day_of_week
- Quality: signal_quality score
- Direction: long/short
Usage:
- train_ml_model() to train
- enable_ml_predictor() to activate
- get_ml_status() for info
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Daily loss limit (2% / $500 max)
- Consecutive loss breaker (3 losses → 2h cooldown)
- Max drawdown circuit breaker (10% threshold)
- News filter with 30min buffer for high-impact events
- Integrated as SCHRITT 0.5 in enhanced_trading_check_wrapper
- Combined lot multiplier with Equity Curve and Reversal Detector
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Added .get() with defaults for total_trades, win_rate, and total_profit
to prevent KeyError when no trades have been logged yet.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Added default values using .get() for all stats fields to prevent
KeyError when no trades have been logged yet.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Previous fix with json.dump didn't preserve the escape sequences correctly.
Using nbformat ensures proper handling of Python string literals in notebook cells.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
The \n characters were incorrectly saved as actual newlines instead
of escaped sequences, causing syntax errors in the print statements.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Allows Equity Curve Trading to actually reduce position sizes when
equity falls below MA. Previously, 50% reduction (0.10 → 0.05) was
blocked by min_lot=0.10, making the soft mode ineffective.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
NEW MODULE: equity_curve_trading.py
- EquityCurveManager class for meta-strategy control
- Tracks equity history after each trade
- Calculates Moving Average over configurable period (default: 10 trades)
- Soft Mode: Reduces lot size to 50% when equity < MA
- Hard Mode: Completely stops trading when equity < MA
- Recovery detection with buffer percentage
- Persistent storage in equity_curve_history.json
CONFIGURATION:
- ma_period: 10 trades (Moving Average window)
- min_trades_required: 5 (warmup period)
- soft_mode: True (reduce lots instead of stopping)
- soft_mode_multiplier: 0.5 (50% lots when under MA)
- recovery_buffer_pct: 0.5% (buffer for recovery status)
INTEGRATION:
- Added to Cell 78 (Advanced Optimizations setup)
- Integrated in enhanced_trading_check_wrapper (Cells 85, 90)
- Added lot_multiplier parameter to execute_trade_v2_adaptive
- Equity update after each successful trade
EXAMPLE FLOW:
1. Before trade: Check should_trade() → returns (allowed, reason, lot_multiplier)
2. If equity < MA: lot_multiplier = 0.5 (or 0.0 in hard mode)
3. Position size adjusted: volume = volume * lot_multiplier
4. After trade: update_equity() called to track new equity
BENEFITS:
- Automatic protection during losing streaks
- Reduces exposure when strategy underperforms
- Capitalizes fully when strategy is working
- No emotional decisions needed
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
PROBLEM:
- execute_trade_v2_adaptive didn't accept pre-calculated signal_info
- Function did its own signal analysis internally
- Trying to pass entry_signal/signal_info caused parameter errors
SOLUTION:
- Added optional parameters: signal_info_override, confidence_override
- If provided, function uses pre-calculated values
- If not provided, function calculates values itself (backward compatible)
CHANGES:
- Cell 28: Added new parameters to function signature
- Cell 28: Use signal_info_override if provided
- Cell 28: Use confidence_override if provided
- Cells 85, 90: Updated execute_trade calls to use new parameters
- activate_enhanced_scoring.py: Updated to use new parameters
Now enhanced_trading_check_wrapper can pass its hybrid confidence
score to execute_trade_v2_adaptive properly.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
CRITICAL BUG:
- extended_top_down_v2_adaptive returns entry_signal as NUMBER (1, -1, 0)
- enhanced_trading_check_wrapper checked for STRINGS ("LONG", "SHORT")
- Result: 1 in ["LONG", "SHORT"] = False → NO TRADES EVER EXECUTED!
FIX:
- Changed: if entry_signal in ["LONG", "SHORT"]
- To: if entry_signal in [1, -1] # 1=LONG, -1=SHORT
- Added signal_direction conversion before execute_trade call
This explains why no trades were being executed despite good signals!
Updated:
- TradingBot_V1.6_Adaptive_Complete_CORRECTED.ipynb (Cells 85, 90)
- activate_enhanced_scoring.py
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
PROBLEM:
- Enhanced Score alone (67.8%) was blocking trades with high Base Confidence (97.5%)
- Low Volume Score (40/100) was dragging down the total
- Good trading setups were being rejected
SOLUTION: Hybrid 60/40 Approach
- Final Score = (Base Confidence × 60%) + (Enhanced Score × 40%)
- The proven trend analysis system keeps primary weight (60%)
- Enhanced scoring still filters bad setups (40%)
EXAMPLE:
- Base Confidence: 97.5%
- Enhanced Score: 67.8%
- OLD: final = 67.8% (blocked at 70% threshold)
- NEW: final = (97.5 × 0.6) + (67.8 × 0.4) = 85.6% (passes!)
BENEFITS:
- Respects the proven base trend system
- Enhanced scoring still adds value
- Fewer false rejections of good trades
- Better balance between filtering and opportunity
Updated files:
- TradingBot_V1.6_Adaptive_Complete_CORRECTED.ipynb (Cells 85, 90)
- activate_enhanced_scoring.py
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
PROBLEM:
- "bad operand type for unary -: 'list'" error
- Line 265 tried to negate a list: support_levels = -support_levels
- _find_peaks() returns a list, not numpy array
- Caused S/R Score to default to 50/100
SOLUTION:
- Changed: support_levels = -support_levels
- To: support_levels = [-s for s in support_levels]
- Negates each element in the list individually
IMPACT:
- S/R Score now calculated correctly
- Enhanced Score will be more accurate
- Better trade filtering
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Fixed invalid format specifier error:
- Cannot use conditional expression inside f-string format specifier
- Changed from: {atr_value:.5f if atr_value else 'N/A'}
- Changed to: separate variable with conditional, then format
This fixes the recurring ERROR in position monitor logs.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
- Updated get_rates() with comprehensive retry logic (3 attempts)
- Added MT5 initialization check before each attempt
- Added symbol visibility check and auto-selection
- Increased wait time to 2 seconds for D1 data loading
- Moved retry logic from get_enhanced_trend_with_retry to get_rates level
- More efficient: retries happen at data source, not wrapper level
This should fix the 'Keine Daten für D1' error during automated trading checks.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Fixed NameError in enhanced trading check:
- check_existing_position() does not exist
- Correct function is check_existing_positions() (with 's')
Fixed in:
- activate_enhanced_scoring.py
- Notebook cells 84 and 89
Error resolved: NameError: name 'check_existing_position' is not defined
Complete guide for Enhanced Signal Scoring activation:
- Quick start (3 steps)
- Before/After comparison
- Test instructions
- Example logs
- Expected improvements
- Troubleshooting
- Success checklist
User can now easily verify and understand the new feature.
SQL 'order' is a reserved keyword causing OperationalError.
Renamed column to 'order_ticket' in both CREATE TABLE and INSERT statements.
Fixes: OperationalError: near "order": syntax error
Added Option D (Enhanced Trailing Stop) to integration guide.
Updated Option E to include all 3 optimizations (B+C+D).
Complete integration examples for:
- Early Breakeven (30%)
- Multi-tier Profit Locking
- ATR-based Trailing
- Time-based Breakeven
- Session-aware Multipliers
🎯 Generated with Claude Code
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Comprehensive documentation of the lot size fix:
- Problem history (5 attempts)
- Root cause analysis
- External config files found
- All changes documented
- Testing procedure
- Python module caching explanation
- Final checklist
KEY INSIGHT:
User was correct - external Python files were the issue:
- advanced_position_management.py had hardcoded 0.01
- Module caching prevented changes from taking effect
- Kernel restart is CRITICAL after .py file changes
🎯 Generated with Claude Code
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
ROOT CAUSE FOUND:
User was right - there was an external config file!
advanced_position_management.py had hardcoded values:
- base_risk = 0.01 (should be 0.02)
- return 0.01 fallback (should be 0.10)
- No min/max lot enforcement
CHANGES:
1. advanced_position_management.py:
✅ base_risk: 0.01 → 0.02 (2% risk)
✅ return fallback: 0.01 → 0.10
✅ volume_min: max(broker_min, 0.10)
✅ volume_max: min(broker_max, 0.20)
2. session_filter_patch.py:
✅ Added lot sizing config:
- min_lot: 0.10
- max_lot: 0.20
- default_lot: 0.10
IMPACT:
- Bot will now use 0.10 minimum lot
- Adaptive sizing respects 0.10-0.20 range
- No more 0.01 lot trades
TESTING NEEDED:
1. Restart kernel
2. Reimport advanced_position_management
3. Verify next trade uses 0.10 lot
🎯 Generated with Claude Code
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
- Complete guide for centralized TRADING_CONFIG
- Step-by-step instructions for changing settings
- Common configuration examples
- Safety warnings and best practices
- Verification checklist
🎯 Generated with Claude Code
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
PROBLEM:
- User identified lot size settings were chaotic and scattered
- Settings across 3 cells (23, 25, 47) caused confusion
- Multiple attempts needed to fix lot size (0.01 → 0.05 → 0.10)
- Quote: "mir kommt das ganze ein bisschen chaotisch vor"
SOLUTION:
✅ Created centralized TRADING_CONFIG in new Cell 6
✅ Updated Cell 25 (calculate_position_size) to use config
✅ Updated Cell 27 (execute_trade_v2_adaptive) to use config
✅ Updated Cell 49 (ADAPTIVE_COMPLETE_CONFIG) to reference config
CONFIGURATION STRUCTURE:
- lot_sizing: min/max/default lot sizes
- risk: max_risk_per_trade, max_positions, max_daily_loss
- confidence: thresholds per session
- atr: base_multiplier, period
- news_filter: enabled, minutes_before/after
- sessions: enabled sessions
- symbols: primary trading symbol
BENEFITS:
✅ Single source of truth for all settings
✅ Easy to find and change configuration
✅ Clear documentation in one place
✅ Prevents scattered hardcoded values
✅ Future changes require only editing Cell 6
FILES:
- centralize_config.py: Script to add config cells
- update_cells_to_use_config.py: Updates cells to use config
NEXT STEPS:
1. Restart kernel in Jupyter
2. Run Cell 6 (TRADING_CONFIG)
3. Run all other cells
4. Verify bot uses 0.10 lot size
🎯 Generated with Claude Code
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>