54 Commits
Author SHA1 Message Date
gavindiazandClaude Code 1a7b0111ad fix(startup): build asyncio socketpair over AF_UNIX - unblocks .bat console freeze
The run_bot.bat console path froze for minutes after two log lines with 0 CPU:
asyncio.run() -> ProactorEventLoop.__init__ -> socket.socketpair() -> Python
3.12 _fallback_socketpair() blocks forever in accept() on the loopback TCP
handshake (security software filters 127.0.0.1 in this interactive console +
xau-trader.exe session). Git-bash redirect runs worked 4/4, proving it is
environment, not interpreter.

Windows 10 17063+ supports AF_UNIX sockets, which need no loopback TCP at all.
Monkey-patch socket.socketpair on win32 to self-pair over AF_UNIX via ctypes
(ws2_32; python.org builds don't expose the AF_UNIX constant), falling back to
the stock socketpair if AF_UNIX is unavailable. socket.socket(fileno=N) treats
N as a raw SOCKET handle on Windows, so the raw handles wrap cleanly.

Verified: smoke test raw pair family=1 + full asyncio.run Proactor loop; the
exe boot went from hang to 'Main loop started' in ~10s.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-21 20:58:08 +08:00
gavindiazandClaude Code f38fa944ea fix(exec): repair the six live loss root causes - cooldown, M5-ATR trailing, honest learner, persisted snapshots
Phase-3 execution-layer fixes, config values are the phase-2 gate winners
(conf=55/breakeven 0.7/atr_trail 1.5/trigger 1.2 - scalping 5-month sweep PF
2.11 at conf=55, baseline PF 1.50):

- trailing_stop: trail now arms only after trail_trigger_atr x ATR unrealized
  gain and never trails past TP (tick-capped). Old logic trailed on H1-ATR
  (~6) while SL/TP were M5-ATR-calibrated (~-6) - breakeven at +1.85 was
  unreachable, every scalp exited at SL
- bot.py: entry cooldown per (strategy, direction) from the cooldown: YAML
  block (scalping 1800s/day_trading 3600s/swing 7200s) - signals were re-firing
  every 30s cycle and piling same-direction positions; Step 4 AI prediction on
  df_m15 (model trains on M15); Step 8 trails on M5 ATR; removed duplicate
  on_trade_closed hook in Step 9 (each external close was learned twice,
  strat_scalping multiplier decayed 0.527->0.41 on garbage inputs);
  performance_snapshots now trigger on wall clock (boot + every >=30min) so
  restarts can't reset the cycle counter to 0
- trade_executor: execute_signal threads ai_score/regime_score into signal
  records; close_trade + sync_positions share _learner_context built from the
  DB Trade row (was: hardcoded regime=RANGING/confluence=75/sentiment=0)
- trading_params.yaml: moderate scalping 50->55, breakeven 0.7, trail 1.5,
  trail_trigger_atr 1.2, cooldown + backtest sections
- tests: scalping moderate confluence assertion 50.0 -> 55.0

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-21 20:57:42 +08:00
gavindiazandClaude Code 7e50a0fef6 feat(llm): provider-agnostic OpenAI-compatible client; FinBERT warm-up off the event loop
Replace the Google Gemini lock-in with a unified chat client usable with any
OpenAI-compatible /v1 endpoint (OpenAI, OpenRouter, DeepSeek, Moonshot, Qwen,
Ollama, Gemini-via-compat...). Switch provider purely via AI_BASE_URL/AI_MODEL.

- ai/llm_client.py (new): lazy openai SDK, per-candidate 429/503/timeout
  failover across AI_MODEL_FAILOVER, robust JSON extraction, reasoning-budget
  retry, image analysis via base64 data URI, singleton get_llm_client()
- settings.py: GeminiSettings -> LLMSettings (api_key/base_url/model/failover/
  vision_model), keeps GEMINI_API_KEY fallback so existing .env keeps working
- news_analyzer.py: analyze_with_gemini -> analyze_with_llm (same output keys);
  FinBERT now loads in a daemon warm-up thread with lexicon fallback - the
  transformers first import was blocking the asyncio main loop 15-45s
  (importlib.metadata full package scan); HF_ENDPOINT hf-mirror setdefault
- telegram_bot.py: news digest + AI-vision chart analysis via the LLM client
- requirements: google-genai -> openai>=1.0; docs/.env.example/README updated
  for the new provider-agnostic setup; dashboard meta updated

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-21 20:56:52 +08:00
gavindiazandClaude Code 886de825fa feat(backtest): real-data gate runners for scalping and day_trading + grid results
The prove-before-live gate tooling. Both runners fetch real MT5 history
(M5/H1 for simulation, M15 for AI, H4 for regime), build zero-lookahead
time-aligned lookups, run the live-parity engine, append config->metrics rows
to grid_results.csv and print the gate verdict:

  expectancy > 0 AND profit_factor >= 1.2 AND max_drawdown_pct <= 15 AND total_trades >= 60

- run_real_backtest.py: scalping gate mirroring live moderate params
- backtest_day_trading_gate.py: H1-frame gate for the day_trading family
  (isolation loop disables scalping/swing), compares conf=live(55) vs
  conf=raw(70); 5-month run: conf=55 PASS (72 trades, WR 70.8%, PF 3.45,
  exp +47.91, maxDD 2.25%), conf=70 FAIL (0 trades - threshold unbeatable)
- grid_results.csv: full scan history incl. the 5-month all-configs sweep
  whose baseline (50/0/2.0: 2214 trades, PF 1.50) proved live losses were
  the execution layer, not the entry spec

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-21 20:56:27 +08:00
gavindiazandClaude Code d9b0b19c02 feat(backtest): live-parity backtest engine with zero-lookahead AI/regime lookups
Phase 1 of the prove-before-live alignment. The backtest engine now mirrors
the live signal path instead of hardcoding HOLD/NEUTRAL:

- predict_batch (signal_classifier): vectorized per-bar AI signals reusing the
  exact live predict() pipeline (class-index mapping, conf<0.5 -> HOLD)
- backtester: per-bar time-aligned AI lookup (M15 close = signal-available
  time, searchsorted, no lookahead), exogenous H4 regime plan with dynamic
  confluence-key deltas, AttentionMarketScorer alignment, per-strategy entry
  cooldown, max-hold timeout exit, breakeven + trailing capped at TP, running-
  equity pnl_pct (was: static initial balance)
- fix: store direction.value on entry (Enum vs str compare silently disabled
  every exit - no trade ever closed)
- fix: _check_mode_sync only clears override on genuine mode transition (grid
  threshold injection was wiped on first read)
- SignalAggregator(use_adaptive_weights=True): backtest uses pure config
  weights so garbage live adaptive weights can't contaminate gate scores

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-21 20:55:45 +08:00
gavindiazandClaude Code 661fd8d941 fix(learner): scope mistake-guard thresholds to each strategy's own confluence base
The guard previously hardcoded the scalping base for every strategy, so
day_trading and swing_trading signals were screened against scalping's
numbers. New _strategy_base_confluence() resolves each strategy to its own
settings section (day_trading_params / swing_trading_params), mirroring
BaseStrategy.min_confluence_score routing; unknown names fall back to
scalping (legacy). Moderate-mode parity verified by smoke test: penalty
override 55+6=61, memory veto 55+8=63 for both day_trading and scalping.
Full suite: 39 tests pass.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-21 20:47:10 +08:00
gavindiazandClaude Code 239f4108df fix(learner): unblock Mistake Guard deadlock — conditional veto + time decay
The guard vetoed UNCONDITIONALLY whenever a strategy multiplier fell below
0.65x, never comparing the confluence the '+6' message claimed. A stale 0.408x
SCALPING multiplier (garbage-era lessons incl. one double-learned duplicate)
then locked the bot out permanently: no trades → no lessons → no recovery.

Now the veto is conditional on confluence >= base + 6 (penalty still applied
to effective_score downstream), and multipliers time-decay back toward 1.0
(~24h constant, persisted without touching win/loss counts).

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-16 17:13:12 +08:00
Mazonia 61d344a3d3 feat: configure dedicated xau-trader.exe process name and Task Manager title v1.0.0 2026-10-06 17:08:03 +00:00
Mazonia 6ee739aea8 feat: add Telegram Mini App (TWA), chart vision scanner & voice command integration for XAUUSD trader bot 2026-10-06 15:27:23 +00:00
Mazonia 1c38457efb Add automated periodic model retraining task to TradingBot scheduler 2026-10-06 09:33:47 +00:00
Mazonia 560f53be5f Update startup script to enable active trading on boot by default and update README 2026-10-04 17:00:57 +00:00
Mazonia 78a7340f6e feat(startup): enable hands-free PC boot standby and Telegram remote control 2026-10-04 15:14:21 +00:00
Mazonia 058926f6ce feat: add dedicated standby mode allowing full remote start/stop from Telegram 2026-10-04 14:57:26 +00:00
Mazonia 79556b806e feat: add remote Telegram start/stop commands and 24/7 background runner scripts 2026-10-04 14:45:15 +00:00
Mazonia 2e5396e92a chore: clean up project files, update gitignore rules and keep data dir 2026-10-04 12:58:08 +00:00
Oduro, Enoch Nana TabiandGitHub 4a72ea7bf8 Update security reporting instructions 2026-10-02 08:33:04 +00:00
Mazonia 1b1257e5dc docs: add CODE_OF_CONDUCT, CONTRIBUTING, LICENSE, and SECURITY policies 2026-10-02 08:17:34 +00:00
Mazonia 9eb0fc2eff fix: set default gemini model to gemini-3.5-flash-lite for instant capacity and sub-second response times 2026-10-01 06:32:10 +00:00
Mazonia b8c286508d feat: add automatic model failover chain for gemini analysis to seamlessly handle 503 capacity spikes 2026-10-01 06:31:08 +00:00
Mazonia 04f604b0a1 fix: update default gemini model to gemini-3.6-flash 2026-10-01 06:26:58 +00:00
Mazonia eb19458ca8 fix: update default gemini model to gemini-1.5-flash to resolve 404 2026-10-01 06:21:38 +00:00
Mazonia bfef04b6de Enhance Telegram Bot with live confluence signals, interactive risk/lot menu, robust HTML entity fallback, and 2025-2026 gold catalysts 2026-10-01 06:11:14 +00:00
Mazonia 82ffae4872 Claude Opus 4.6 improvements: MT5 concurrency fixes, timezone UTC fixes, sentiment scoring consistency, security validator, and 2025-2026 economic/gold lexicon updates 2026-10-01 05:59:13 +00:00
Mazonia 600210cbf0 feat: show active trading profile mode in bot startup Telegram message 2026-09-27 22:38:43 +00:00
Mazonia 6ad2d46851 fix(trades): resolve datetime offset naive/aware bug and restore /trades command and real-time realized PnL 2026-09-25 14:22:33 +00:00
Mazonia 284ef3ec62 feat(telegram): register native menu commands, add mode switching to main menu and help cheatsheet 2026-09-25 01:11:23 +00:00
Mazonia 3bb4c82e20 Implement dynamic Mode Switching (Safe/Moderate/Aggressive), Fix MT5 Zero-Margin Trap, decouple Confluence threshold, and add comprehensive mode-switching tests with false-pretense protection 2026-09-25 00:58:45 +00:00
Mazonia a45f9cde8e Sanitize API keys in logs 2026-09-22 03:37:35 +00:00
Mazonia fc581a1eae Graceful WebSocket disconnect and HF warning suppression in run.bat 2026-09-21 23:01:16 +00:00
Mazonia ea4d66db69 Configure FinBERT pipeline with top_k=None and robust score extraction 2026-09-21 22:55:21 +00:00
Mazonia c148ab26f3 Fix FinBERT fallback, Gemini rate limit cooldown, RegimeAnalysis attribute, and port handling 2026-09-21 22:45:59 +00:00
Mazonia 079d6d88e7 Fix MT5 connection stability and resolve API errors 2026-09-21 22:38:17 +00:00
Mazonia 944955f194 docs: update README with Temporal Self-Attention, stationarity features, news deduplication & dashboard features 2026-09-21 18:57:51 +00:00
Mazonia 6f5636de23 feat(ai): integrate neural network book enhancements: temporal self-attention scorer, candlestick physics & stationarity features, and dynamic regime-adaptive threshold 2026-09-21 14:24:18 +00:00
Mazonia 219b72578c fix(news): implement persistent multi-layer deduplication, word-boundary keyword matching, and alert suppression 2026-09-21 13:10:36 +00:00
Mazonia 355104133f feat(orders): add Autonomous Pending Order Guardian to auto-cancel limit orders upon AI invalidation, macro shocks, or stale drift 2026-09-21 13:02:34 +00:00
Mazonia ece5a792c2 fix(sync): live MT5 broker deal history sync for recent trades table, realized P&L calculations, and win-rate metrics 2026-09-21 12:55:06 +00:00
Mazonia 6e5c97e91f feat(chart): render open positions, SL/TP levels, and pending limit orders directly on candlestick chart with interactive toggle 2026-09-21 11:25:13 +00:00
Mazonia 12ca311382 fix(logging): enforce UTF-8 stdout encoding to support unicode telemetry on Windows 2026-09-21 11:18:59 +00:00
Mazonia 9591f67cd5 feat(quant): institutional dashboard overhaul, live auto-sync chart, Smart Midway Exit Guardian, and 10k MT5 candle AI training 2026-09-21 11:17:37 +00:00
Mazonia 1725f4c829 feat(dashboard): comprehensive UI/UX overhaul, order mode switcher (market vs scheduled limit), pending orders table with cancel action, and fix /api/learning 404 2026-09-21 10:48:28 +00:00
Mazonia 312b78201b fix(telegram): render scheduled pending orders, add cancel button, add Self-Learning button to main keyboard, and register native menu commands via set_my_commands 2026-09-21 10:27:48 +00:00
Mazonia e8b349ccf0 feat: complete AI model training pipeline, MT5 live order execution, and scheduled pending orders
- Implemented scripts/train_ai.py for institutional XGBoost training on MT5 historical candles
- Integrated 46 multi-indicator features, TimeSeriesSplit validation, and feature importance drivers
- Added --train-only and improved --train in main.py
- Enabled MT5 AutoTrading configuration ([Experts] AllowLiveTrading=1)
- Added send_pending_order and cancel_order to MT5Connector (BUY_LIMIT, SELL_LIMIT, BUY_STOP, SELL_STOP)
- Added automatic 12-hour periodic model retraining job in BotScheduler and TradingBot
- Updated Telegram Command Center with MT5 standalone fallback and pending order telemetry
- Placed live test BUY market trade and scheduled BUY_LIMIT order on XAUUSD
2026-09-21 10:13:52 +00:00
Mazonia a7a2b93985 feat: implement autonomous self-learning and mistake adaptation engine
- Implemented TradeLearner with post-mortem mistake diagnostics and defensive rule formulation
- Added Mistake Memory Guard to screen prospective signals against past loss patterns and traps
- Dynamic Multi-Armed Bandit strategy multipliers (Scalping, Day, Swing) and adaptive confluence weighting
- Integrated with TradeExecutor, Bot position synchronization, and SignalAggregator
- Real-time Self-Learning HUD in modern glassmorphic web dashboard (/api/learning)
- Added /learning command and interactive callback button to Telegram Command Center
- Added TradeLesson and AdaptiveWeight persistence models in SQLite WAL database
- Updated documentation and README
2026-09-21 09:53:45 +00:00
Mazonia c76a98117d feat: resilient news sentiment, on-demand regime detection, and institutional glassmorphic dashboard UI 2026-09-21 09:46:45 +00:00
Mazonia 4ece88393f fix(telegram): resolve closeall confirmation freeze, non-blocking MT5 reconnect, and handle Message is not modified 2026-09-21 02:17:48 +00:00
Mazonia abe5b0298c security: complete cross-platform communication security and technical audit 2026-09-21 02:05:50 +00:00
Mazonia 39eb5d1af6 docs: update README with architecture, Telegram Command Center, and batch launchers 2026-09-21 01:57:50 +00:00
Mazonia be48ea97b4 Integrate economic event cooldowns, background scheduler, MT5 deal history syncing, trailing stop memory cleanup, and non-blocking dashboard API 2026-09-21 01:56:00 +00:00
Mazonia ad1b21fe6d Optimize execution latency: zero-delay Telegram long polling, broker filling mode auto-detection, and safe close handlers 2026-09-21 01:34:14 +00:00