9.7 KiB
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:
- Analysis Phase: Each agent analyzes market data and produces individual signals
- Interaction Phase: Agents communicate and combine their signals
- 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:
-
Hurst Agent (RegimeDetector):
- Calculates Hurst exponent using DFA/R/S analysis
- Updates
SHARED_regimeHandSHARED_regimeZ - Period dynamically adjusted based on data length
-
ADX Agent (RegimeADX):
- Calculates ADX using native MT5 function
- Normalizes ADX to z-score
- Updates
SHARED_adxZandSHARED_adxRaw
-
MA Agent (MAAgent):
- Calculates price-to-MA ratio
- Computes slope of MA
- Combines signals using variance weighting
- Updates
lastZScore(local, not shared)
-
Momentum Agent (MomentumAgent):
- Calculates momentum and acceleration
- Computes z-scores for both
- Combines signals using variance weighting
- Updates
lastZScore(local, not shared)
-
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
- Called by orchestrator during
-
Pattern Hunter Agent (PatternHunter):
- Called by orchestrator during
Interact()phase - Analyzes historical patterns
- Updates
lastZScore(local, not shared)
- Called by orchestrator during
Phase 2: Orchestration
The orchestrator combines agent signals using a sophisticated softmax gating mechanism:
-
Signal Collection:
- Collects z-scores from all agents
- Filters out disabled agents
-
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
-
Combined Signal:
- Applies softmax to get weighted agent contributions
- Applies tanh to normalize to [-1, 1]
- Updates
combinedZandcombinedZStats
Phase 3: Market Decision
-
Entry Signal:
- Combined z-score compared to
minActionableZ minActionableZ = combinedZStats.Std()(empirical)- Fallback: 0.5 (when stats not ready)
- Combined z-score compared to
-
Position Sizing:
- Base lot:
AdaptiveBaseLot() - Adjusted by entry z-score magnitude
- Capped by broker limits
- Base lot:
-
Risk Management:
- SL:
AdaptiveSL()= returnStats.Std() - TP:
AdaptiveTP()=AdaptiveSL() * RR ratio - RR ratio:
1.0 / (1.0 - winRate)
- SL:
Market Entry/Exit Logic
Entry Conditions
The system enters a trade when:
-
Signal Strength:
|combinedZ| > minActionableZminActionableZ = combinedZStats.Ready() ? combinedZStats.Std() : 0.5- This ensures we only trade when the signal is statistically significant
-
Position Direction:
dir = 1ifcombinedZ > thrdir = -1ifcombinedZ < -thrthr = (overrideMinZ > 0) ? overrideMinZ : AdaptiveMinZ()
-
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) orentryPrice - (atr * tpMult)(short) - tpMult:
AdaptiveTP() / atr
Stop Loss (SL)
- Trigger: Price reaches SL level
- SL Level:
entryPrice - (atr * slMult)(long) orentryPrice + (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
-
Hurst Agent Output:
SHARED_regimeH = 0.6(trending market)SHARED_regimeZ = 0.8(strong bullish signal)
-
ADX Agent Output:
SHARED_adxZ = 0.7(strong trend)SHARED_adxRaw = 35.0(strong trend strength)
-
Consensus Agent Processing:
hurstZ = 0.8,adxZ = 0.7hStd = 0.5,aStd = 0.5combinedScale = √(0.5² + 0.5²) = 0.707agreement = 1.0 - (0.1 / 0.707) = 0.86SHARED_regimeConsensus = tanh((0.8 + 0.7) / 2 * 0.86) = 0.94- Pattern:
strong_trend(pCode = 1)
Example 2: Pattern Hunter Interaction
-
Pattern Hunter Inputs:
hurst = 0.8,adx = 0.7,ma = 0.3,mom = 0.9tH = 0.5,tA = 0.5,tM = 0.4,tM2 = 0.6
-
Pattern Detection:
maMomAgree = (0.3 * 0.9 > 0.4 * 0.6) = trueregimeTrend = (0.8 + 0.7) > 0.707 = truemomAccel = (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.70patternStrength = 1.0 - exp(-1.70) = 0.82
Example : Market Entry
-
Combined Signal:
combinedZ = 0.94(from consensus)minActionableZ = 0.5(from combinedZStats)- Entry:
|0.94| > 0.5✓
-
Position Sizing:
balance = 10000winRate = 0.6,maxDrawdown = 0.2,sharpeBonus = 0.8riskFrac = 0.6 * (1 - 0.2) * (0.5 + 0.8 * 0.5) = 0.6 * 0.8 * 0.9 = 0.432riskFrac = MathMax(0.002, MathMin(0.02, 0.432)) = 0.02lot = 10000 * 0.02 / 100000 = 0.2lot = 0.2 * MathAbs(0.94) = 0.188
-
SL/TP:
ATR = 0.02SL = entryPrice - 0.02 * 1.5 = entryPrice - 0.03TP = entryPrice + 0.02 * 2.5 = entryPrice + 0.05
Error Handling and Recovery
Data Issues
-
Insufficient Data:
- Wait for minimum samples before using statistics
- Use fallback values when data insufficient
-
Division by Zero:
- Use
DATA_EPS()for safe division - Check for zero variance before calculations
- Use
-
Invalid Values:
- Validate all input data
- Use reasonable defaults for invalid values
- Validate all input data
Recovery Mechanisms
-
Model Reload:
- Automatic reload on startup if save file exists
- Graceful degradation if save file corrupted
-
State Reset:
- Reset all statistics on error
- Log errors for debugging
Performance Monitoring
Key Metrics
-
Trading Performance:
- Win rate
- Average win/loss ratio
- Maximum drawdown
- Sharpe ratio
-
System Performance:
- Agent weight convergence
- Signal strength statistics
- Processing time
- Memory usage
Health Monitoring
-
Orchestrator Health:
PrintAgentStatus(): Shows all agent signals and weightsLogHealth(): Shows rolling performance metricsLogBarHistory(): Stores historical signals
-
Agent Health:
- Each agent has
SignalInfo()method - Shows agent name, z-score, and statistics
- Helps identify underperforming agents
- Each agent has
Future Enhancements
-
Advanced Features:
- Multi-timeframe analysis
- Machine learning for pattern recognition
- Natural language processing for news sentiment
-
Risk Management:
- Dynamic position sizing based on volatility
- Correlation-based risk limits
- Market regime-specific risk adjustments
-
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.