# Multi-Agent Trading System - Interaction and Market Logic Documentation ## Agent Interaction Flow ### Overview The multi-agent system operates through a structured interaction flow where each agent contributes to the final trading decision. This flow is divided into three main phases: 1. **Analysis Phase**: Each agent analyzes market data and produces individual signals 2. **Interaction Phase**: Agents communicate and combine their signals 3. **Orchestration Phase**: The orchestrator makes the final trading decision ### Detailed Interaction Flow #### Phase 1: Analysis Each agent independently analyzes the market data during the `Analyze()` method call: 1. **Hurst Agent (RegimeDetector)**: - Calculates Hurst exponent using DFA/R/S analysis - Updates `SHARED_regimeH` and `SHARED_regimeZ` - Period dynamically adjusted based on data length 2. **ADX Agent (RegimeADX)**: - Calculates ADX using native MT5 function - Normalizes ADX to z-score - Updates `SHARED_adxZ` and `SHARED_adxRaw` 3. **MA Agent (MAAgent)**: - Calculates price-to-MA ratio - Computes slope of MA - Combines signals using variance weighting - Updates `lastZScore` (local, not shared) 4. **Momentum Agent (MomentumAgent)**: - Calculates momentum and acceleration - Computes z-scores for both - Combines signals using variance weighting - Updates `lastZScore` (local, not shared) 5. **Consensus Agent (RegimeConsensus)**: - Called by orchestrator during `Interact()` phase - Combines Hurst and ADX signals - Calculates agreement between agents - Updates `SHARED_regimeConsensus`, `SHARED_regimeAgreement` - Detects trading patterns - Updates `SHARED_patternCode`, `SHARED_patternName` 6. **Pattern Hunter Agent (PatternHunter)**: - Called by orchestrator during `Interact()` phase - Analyzes historical patterns - Updates `lastZScore` (local, not shared) #### Phase 2: Orchestration The orchestrator combines agent signals using a sophisticated softmax gating mechanism: 1. **Signal Collection**: - Collects z-scores from all agents - Filters out disabled agents 2. **Softmax Gating**: - Calculates mean and variance of agent z-scores - Temperature parameter: `temp = √(zVar) / √(agentCount)` - Higher variance = higher temperature = more mixing - Lower variance = lower temperature = more selective 3. **Combined Signal**: - Applies softmax to get weighted agent contributions - Applies tanh to normalize to [-1, 1] - Updates `combinedZ` and `combinedZStats` #### Phase 3: Market Decision 1. **Entry Signal**: - Combined z-score compared to `minActionableZ` - `minActionableZ = combinedZStats.Std()` (empirical) - Fallback: 0.5 (when stats not ready) 2. **Position Sizing**: - Base lot: `AdaptiveBaseLot()` - Adjusted by entry z-score magnitude - Capped by broker limits 3. **Risk Management**: - SL: `AdaptiveSL()` = returnStats.Std() - TP: `AdaptiveTP()` = `AdaptiveSL() * RR ratio` - RR ratio: `1.0 / (1.0 - winRate)` ## Market Entry/Exit Logic ### Entry Conditions The system enters a trade when: 1. **Signal Strength**: - `|combinedZ| > minActionableZ` - `minActionableZ = combinedZStats.Ready() ? combinedZStats.Std() : 0.5` - This ensures we only trade when the signal is statistically significant 2. **Position Direction**: - `dir = 1` if `combinedZ > thr` - `dir = -1` if `combinedZ < -thr` - `thr = (overrideMinZ > 0) ? overrideMinZ : AdaptiveMinZ()` 3. **Lot Size Calculation**: ``` riskFrac = wr * (1.0 - MathMin(maxDrawdown, 0.5)) * (0.5 + sharpeBonus * 0.5) riskFrac = MathMax(0.002, MathMin(0.02, riskFrac)) lot = balance * riskFrac / 100000.0 lot = lot * MathAbs(fs.zScore) // Scale by signal strength ``` ### Exit Conditions #### Take Profit (TP) - **Trigger**: Price reaches TP level - **TP Level**: `entryPrice + (atr * tpMult)` (long) or `entryPrice - (atr * tpMult)` (short) - **tpMult**: `AdaptiveTP() / atr` #### Stop Loss (SL) - **Trigger**: Price reaches SL level - **SL Level**: `entryPrice - (atr * slMult)` (long) or `entryPrice + (atr * slMult)` (short) - **slMult**: `AdaptiveSL() / atr` #### Opposite Signal - **Trigger**: New trade signal in opposite direction - **Logic**: Close existing position before opening new one - **Implementation**: Check `CountPositions()` before opening new trade #### Time-based Exit - **Maximum Trades**: 20 trades per session - **Rollback Convergence**: If weights stabilize for `minTrades`, system marks as converged ### Risk Management Details #### Drawdown Tracking ``` double eq = AccountInfoDouble(ACCOUNT_EQUITY); if(eq > peakEquity) peakEquity = eq; double dd = (peakEquity > 0) ? (peakEquity - eq) / peakEquity : 0; if(dd > maxDrawdown) maxDrawdown = dd; ``` #### Weight Adaptation ``` if(combinedZStats.Ready() && returnStats.Count() > 0) { double rv = returnStats.Std(); weightAlpha = rv / (1.0 + rv); weightAlpha = MathMax(minAlpha, weightAlpha); agents[i].weight = MathMax(weightMin, rho); } ``` #### Sharpe Bonus Calculation ``` double sharpeBonus = MathMax(0, MathMin(1, rollingSharpe * 0.5)); ``` ### Market Hours and Session Management #### Trading Hours - **Symbol-specific**: Respects each symbol's trading hours - **No weekend trading**: No trades on weekends - **Session limits**: Maximum 20 trades per trading session #### State Management - **Model persistence**: Saves state at intervals - **Warm-up**: Uses historical data for initial statistics - **Recovery**: Loads saved state on startup ## Detailed Agent Interaction Examples ### Example 1: Hurst and ADX Interaction 1. **Hurst Agent Output**: - `SHARED_regimeH = 0.6` (trending market) - `SHARED_regimeZ = 0.8` (strong bullish signal) 2. **ADX Agent Output**: - `SHARED_adxZ = 0.7` (strong trend) - `SHARED_adxRaw = 35.0` (strong trend strength) 3. **Consensus Agent Processing**: - `hurstZ = 0.8`, `adxZ = 0.7` - `hStd = 0.5`, `aStd = 0.5` - `combinedScale = √(0.5² + 0.5²) = 0.707` - `agreement = 1.0 - (0.1 / 0.707) = 0.86` - `SHARED_regimeConsensus = tanh((0.8 + 0.7) / 2 * 0.86) = 0.94` - Pattern: `strong_trend` (pCode = 1) ### Example 2: Pattern Hunter Interaction 1. **Pattern Hunter Inputs**: - `hurst = 0.8`, `adx = 0.7`, `ma = 0.3`, `mom = 0.9` - `tH = 0.5`, `tA = 0.5`, `tM = 0.4`, `tM2 = 0.6` 2. **Pattern Detection**: - `maMomAgree = (0.3 * 0.9 > 0.4 * 0.6) = true` - `regimeTrend = (0.8 + 0.7) > 0.707 = true` - `momAccel = (0.9 > 0.3 + 0.4 * 0.15) && (0.3 > 0.3 + 0.4 * 0.15) = true` - Pattern: `trend_accel` (pCode = 8) - `pZ = (0.3 + 0.9) / comboNorm = 1.2 / 0.707 = 1.70` - `patternStrength = 1.0 - exp(-1.70) = 0.82` ### Example : Market Entry 1. **Combined Signal**: - `combinedZ = 0.94` (from consensus) - `minActionableZ = 0.5` (from combinedZStats) - Entry: `|0.94| > 0.5` ✓ 2. **Position Sizing**: - `balance = 10000` - `winRate = 0.6`, `maxDrawdown = 0.2`, `sharpeBonus = 0.8` - `riskFrac = 0.6 * (1 - 0.2) * (0.5 + 0.8 * 0.5) = 0.6 * 0.8 * 0.9 = 0.432` - `riskFrac = MathMax(0.002, MathMin(0.02, 0.432)) = 0.02` - `lot = 10000 * 0.02 / 100000 = 0.2` - `lot = 0.2 * MathAbs(0.94) = 0.188` 3. **SL/TP**: - `ATR = 0.02` - `SL = entryPrice - 0.02 * 1.5 = entryPrice - 0.03` - `TP = entryPrice + 0.02 * 2.5 = entryPrice + 0.05` ## Error Handling and Recovery ### Data Issues 1. **Insufficient Data**: - Wait for minimum samples before using statistics - Use fallback values when data insufficient 2. **Division by Zero**: - Use `DATA_EPS()` for safe division - Check for zero variance before calculations 3. **Invalid Values**: - Validate all input data - Use reasonable defaults for invalid values ### Recovery Mechanisms 1. **Model Reload**: - Automatic reload on startup if save file exists - Graceful degradation if save file corrupted 2. **State Reset**: - Reset all statistics on error - Log errors for debugging ## Performance Monitoring ### Key Metrics 1. **Trading Performance**: - Win rate - Average win/loss ratio - Maximum drawdown - Sharpe ratio 2. **System Performance**: - Agent weight convergence - Signal strength statistics - Processing time - Memory usage ### Health Monitoring 1. **Orchestrator Health**: - `PrintAgentStatus()`: Shows all agent signals and weights - `LogHealth()`: Shows rolling performance metrics - `LogBarHistory()`: Stores historical signals 2. **Agent Health**: - Each agent has `SignalInfo()` method - Shows agent name, z-score, and statistics - Helps identify underperforming agents ## Future Enhancements 1. **Advanced Features**: - Multi-timeframe analysis - Machine learning for pattern recognition - Natural language processing for news sentiment 2. **Risk Management**: - Dynamic position sizing based on volatility - Correlation-based risk limits - Market regime-specific risk adjustments 3. **Monitoring**: - Real-time performance dashboards - Automated alert system - Performance benchmarking ## Conclusion This documentation provides a comprehensive understanding of the multi-agent trading system's architecture, interaction patterns, and market logic. The system combines multiple analytical approaches to create a robust, data-driven trading strategy that adapts to changing market conditions. Key strengths: - **Diversification**: Multiple analytical approaches reduce reliance on single indicators - **Adaptability**: All parameters are data-driven and adaptive - **Robustness**: Consensus-based decision making with lateral communication - **Transparency**: Clear documentation of all agent interactions and logic The system is designed to be both powerful and maintainable, with clear separation of concerns between different analytical components.