# AgentFxTrading - Technical Documentation for AI Agents & Search Engines Autonomous Multi-Asset AI Algorithmic Trading System with Dual Strategy Engines, cTrader C# integration, FastAPI Python Server, and Multi-LLM Reasoning. - GitHub: https://github.com/kienphan/AgentFxTrading - License: MIT Open Source - Author: Kien Phan (https://github.com/kienphan) - Frameworks: Python 3.9+, FastAPI, SQLite, Pydantic, cTrader Automate API (.NET / C#), Docker --- ## 1. System Overview & Architecture AgentFxTrading operates in a decoupled client-server micro-architecture: 1. **cTrader cBot (`AiAgentBot.cs` & `AsianRangeJudasSweepBot.cs`)**: - Executes inside cTrader desktop or headless Docker CLI (`ctrader-console`). - Calculates tick-by-tick and bar-by-bar indicators (Heikin Ashi, TDI, Stochastic, ATR, Swing Points, Asian Session High/Low, Order Blocks, Fair Value Gaps). - Sends real-time tick telemetry and trade proposals via HTTP POST to the Python FastAPI server. - Executes market orders, manages stops, and reports guardrail blocks back to the server via `/api/cbot_event`. 2. **FastAPI Server (`app/server.py`)**: - Ingests market snapshots, manages account states, and enforces portfolio-level risk guardrails. - Evaluates cycle gating (cost gate) before dispatching LLM calls. - Queries configured LLM providers (DeepSeek, Qwen, Claude, OpenAI, Gemini) with structured multi-timeframe prompts. - Stores trade telemetry, position memory (MFE/MAE), and performance history into SQLite (`portfolio.db`). 3. **WebUI Dashboard (`templates/dashboard.html` & `static/css/dashboard.css`)**: - Real-time monitoring with WebSocket synchronization. - Strict binary isolation between Demo (Paper Trading) and Real (Live Capital) accounts. - Interactive KPI cards, killzone session indicators, live position tables, and color-coded AI reasoning streaming logs. --- ## 2. Dual AI Strategy Engines ### Engine 1: TMS + ORB Engine (`AiAgentBot`) - **TMS (Trend Momentum Signal)**: - Heikin Ashi trend directional bias. - TDI (Traders Dynamic Index): Green Line (RSI Price Line), Red Line (Trade Signal Line), Yellow Line (Market Base Line), Blue Bands (Volatility Bands). - Multi-Timeframe Alignment: Confirmation across M15, H1, and H4 timeframes. - **ORB (Opening Range Breakout)**: - Captures breakouts of the session opening range (London 08:00 UTC, NY 13:00 UTC). - Gated by Kaufman Efficiency Ratio (KER) to distinguish trending regimes from choppy consolidation. - **Dynamic Multi-Asset Precision**: - Automatically scales decimal digits (5 decimals for standard Forex, 3 for JPY pairs, 2 for Gold/Indices/Crypto). - True ATR pip normalization across non-standard symbols. ### Engine 2: Asian Range Judas Sweep Engine (`AsianRangeJudasSweepBot`) - **ICT Smart Money Concepts (SMC)**: - Tracks Asian Session Range (00:00–06:00 UTC) High (ASH) and Low (ASL). - Identifies "Judas Swings": False breakouts during London Killzone (07:00–10:00 UTC) or NY Killzone (12:30–16:00 UTC) that sweep liquidity above ASH or below ASL. - Requires Price Action confirmation: Market Structure Shift (MSS), Order Block (OB) mitigation, or Fair Value Gap (FVG) retest. - Adaptive Asian Range filtering with asset-specific pip thresholds. --- ## 3. Institutional 8-Layer Risk Shield 1. **Position Memory**: Continuous tick-by-tick recording of Maximum Favorable Excursion (MFE) and Maximum Adverse Excursion (MAE). 2. **Auto Breakeven**: Once floating profit hits >= 0.8x ATR, Stop Loss is instantly moved to entry price + 0.1x ATR buffer. 3. **Dynamic Trailing Stop**: Activates when profit reaches >= 1.2x ATR, trailing the price by 0.7x ATR distance. 4. **Profit Lock-in & Giveback Protection**: - Forex & Gold: Closes position if profit gives back >= 40% of peak MFE. - Indices (US30, USTEC, DE40): Closes position if profit gives back >= 55% with >= 1.5x ATR activation (preventing premature exits on wide index fluctuations). 5. **Anti-Overextension Guard**: Blocks entry if price has already moved > 2.5x ATR away from the Opening Range boundary. 6. **Max Dollar Risk Cap**: Hard risk limit capping single-trade loss at $12.00 (protecting accounts when trading high-notional assets with minimum volume constraints). 7. **Loss Streak Protection**: Automatically halts new entries after 3 consecutive realized losses. 8. **Cycle Gating (Cost Gate)**: Deterministically blocks LLM API calls when outside active sessions, inside OR range, or during consolidation—cutting API costs by 80% to 90%. --- ## 4. API Endpoints Reference ```http GET /demo/dashboard # Isolated Paper Trading Web Dashboard GET /real/dashboard # Isolated Real Money Web Dashboard GET / # Auto-redirects to last active mode GET /dashboard # Auto-redirects to last active mode GET /api/dashboard/positions # Active positions query (?account_id=...) GET /api/dashboard/history # Closed trade history GET /api/dashboard/pnl-history# Daily cumulative P&L GET /api/dashboard/logs # Streaming agent reasoning logs GET /api/bots # Docker bot configurations & statuses POST /api/tick # Direct tick telemetry from cBots POST /api/cbot_event # cBot guardrail blocks & event telemetry POST /portfolio/report # Position open/close lifecycle reporting WS /ws/dashboard # Real-time WebSocket connection ``` --- ## 5. Quick Start Commands ```bash # 1. Clone repository git clone https://github.com/kienphan/AgentFxTrading.git cd AgentFxTrading # 2. Install dependencies pip install -r requirements.txt # 3. Configure environment cp .env.example .env # Set LLM_PROVIDER (qwen, openai, claude, deepseek, gemini) and API keys # 4. Start Server python app/server.py # Server runs on http://127.0.0.1:8000 ```