Skip to content

Astralchemist/PowerLawsEA

Repository files navigation

Power Laws Expert Advisor (EA) Series

A comprehensive collection of MetaTrader 5 Expert Advisors and indicators based on power law distributions, criticality theory, and extreme value analysis for advanced algorithmic trading.

📋 Overview

This repository contains multiple MQL5 trading systems that leverage mathematical concepts from complexity science, statistical physics, and extreme value theory to identify high-probability trading opportunities in financial markets.

Key Concepts

  • Power Laws: Mathematical relationships where one quantity varies as a power of another, commonly found in financial market distributions
  • Criticality Theory: Analysis of systems approaching critical phase transitions, applicable to market regime changes
  • St. Petersburg Paradox: A probability theory paradox used to model extreme value scenarios in trading
  • Self-Organized Criticality: Framework for understanding how markets naturally evolve toward critical states

🚀 Expert Advisors & Indicators

1. PowerLaws EA (powerlaws.mq5)

The main power law-based trading system that analyzes price distributions to identify fat-tailed events and trading opportunities.

Features:

  • Power law exponent (alpha) calculation
  • Fat-tail event detection
  • Regime change identification
  • Adaptive position sizing based on distribution characteristics

2. Power Law Criticality EA (PowerLawCriticalityEA.mq5)

Advanced EA combining power law analysis with criticality theory to detect market phase transitions.

Features:

  • Self-organized criticality detection
  • Cascade probability calculation
  • Imbalance acceleration tracking
  • Volatility compression analysis
  • Multi-component criticality scoring
  • Visual dashboard with real-time metrics
  • Automated signal generation with arrows

Key Indicators:

  • Alpha (α): Power law exponent (lower values indicate fatter tails)
  • Criticality Score: Combined measure of market stress
  • Cascade Probability: Likelihood of large price movements
  • Imbalance Acceleration: Rate of change in buy/sell pressure

3. Power Law Criticality Indicator (PowerLawCriticality.mq5)

Standalone indicator version for manual trading and analysis.

4. Power Laws of Extremes EA (powerlawsofextremes.mq5)

Specialized EA focusing on extreme value theory and tail risk analysis.

Features:

  • Extreme value distribution fitting
  • Tail risk quantification
  • Black swan event detection
  • Risk-adjusted position sizing

5. St. Petersburg Paradox EA (StPetersburgParadox.mq5)

Trading system based on the St. Petersburg paradox, designed for optimal bet sizing in scenarios with unlimited upside potential.

Features:

  • Kelly criterion implementation
  • Utility-based position sizing
  • Expected value optimization
  • Risk of ruin calculations

6. PowerEA Fixed (PowerEA_Fixed.mq5)

Refined and optimized version of the base power law EA with bug fixes and performance improvements.

📊 How It Works

Power Law Analysis

The systems calculate the power law exponent (α) from price change distributions:

P(x) ∝ x^(-α)

Where:

  • α > 3: Normal market conditions (thin tails)
  • α = 2-3: Moderate fat tails (increased risk)
  • α < 2: Extreme fat tails (high probability of large moves)

Criticality Detection

The criticality EA combines multiple signals:

  1. Volatility Compression: Bollinger Band width percentile
  2. Imbalance Acceleration: Rate of change in order flow
  3. Alpha Deviation: Distance from normal distribution (α = 3)

Criticality Score = (Compression × 0.4) + (|Acceleration| × 0.3) + (Alpha Deviation × 0.3)

Signal Generation

Signals are generated when:

  • Criticality score exceeds threshold (default: 0.7)
  • Cascade probability is high (default: > 0.6)
  • Clear directional bias exists in imbalance

⚙️ Installation

  1. Download Files: Clone or download this repository
  2. Copy to MT5:
    • Copy .mq5 files to MQL5/Experts/ or MQL5/Indicators/
    • Copy .ex5 files (compiled) to the same directories
  3. Compile (if needed): Open in MetaEditor and compile
  4. Attach to Chart: Drag and drop onto your desired chart

🔧 Configuration

Power Law Criticality EA Parameters

// Analysis Parameters
input int    InpLookbackPeriod = 100;        // Lookback for alpha calculation
input int    InpImbalancePeriod = 20;        // Period for imbalance calculation
input int    InpBBPeriod = 20;               // Bollinger Bands period
input double InpBBDeviation = 2.0;           // Bollinger Bands deviation

// Signal Parameters
input double InpCascadeThreshold = 0.6;      // Minimum cascade probability
input double InpCriticalityThreshold = 0.7;  // Minimum criticality score

// Display Options
input bool   InpShowDashboard = true;        // Show information dashboard
input bool   InpShowSignalArrows = true;     // Show signal arrows on chart
input bool   InpShowAlerts = true;           // Enable alert notifications

Recommended Settings by Timeframe

Timeframe Lookback Imbalance Period BB Period
M15 50 10 20
H1 100 20 20
H4 200 30 30
D1 500 50 50

📈 Trading Strategy

Entry Signals

Bullish Setup:

  • Criticality score > threshold
  • Cascade probability > threshold
  • Buy imbalance > 0.6
  • Positive imbalance acceleration

Bearish Setup:

  • Criticality score > threshold
  • Cascade probability > threshold
  • Buy imbalance < 0.4
  • Negative imbalance acceleration

Risk Management

The system provides adaptive risk multipliers:

Risk Multiplier = (3.0 - α) / 0.5
  • α = 3.0: 1.0× (normal risk)
  • α = 2.5: 2.0× (increased position size)
  • α = 2.0: 3.0× (maximum position size)

Take Profit Optimization

TP Multiplier = 1.0 + (Cascade Probability - 0.5) × 4.0

Higher cascade probability suggests larger potential moves, warranting wider take profit targets.

📚 Theoretical Background

Power Laws in Finance

Financial markets exhibit power law distributions in:

  • Price returns (especially in tails)
  • Trading volumes
  • Volatility clustering
  • Drawdown magnitudes

Self-Organized Criticality

Markets naturally evolve toward critical states where:

  • Small events can trigger large cascades
  • System becomes highly sensitive to perturbations
  • Predictability increases near critical points

Applications

  • Regime Detection: Identify transitions between normal and critical states
  • Risk Management: Adjust position sizing based on tail risk
  • Timing: Enter trades when cascade probability is elevated
  • Exit Strategy: Scale out as criticality decreases

🔬 Backtesting & Optimization

Recommended Approach

  1. In-Sample Period: Use 70% of historical data for optimization
  2. Out-of-Sample: Validate on remaining 30%
  3. Walk-Forward: Regular re-optimization (quarterly)
  4. Monte Carlo: Test robustness with randomized data

Key Metrics to Monitor

  • Sharpe Ratio: Risk-adjusted returns
  • Maximum Drawdown: Worst peak-to-trough decline
  • Profit Factor: Gross profit / gross loss
  • Win Rate: Percentage of profitable trades
  • Average Win/Loss Ratio: Size of wins vs. losses

⚠️ Risk Disclaimer

IMPORTANT: These Expert Advisors are provided for educational and research purposes only.

  • Past performance does not guarantee future results
  • Trading involves substantial risk of loss
  • Only trade with capital you can afford to lose
  • Test thoroughly on demo accounts before live trading
  • Power law analysis can fail during unprecedented market events
  • Always use appropriate risk management and position sizing

🛠️ Development & Customization

Extending the EAs

The code is modular and can be extended:

// Example: Add custom criticality component
double CalculateCustomComponent(int currentBar) {
    // Your custom logic here
    return customScore;
}

// Integrate into criticality calculation
double CalculateCriticality(...) {
    double customScore = CalculateCustomComponent(currentBar);
    return (compressionScore * 0.3) + 
           (accelScore * 0.3) + 
           (alphaDev * 0.2) + 
           (customScore * 0.2);
}

Export Functions

The Criticality EA exports functions for use by other EAs:

double PLC_GetAlpha();              // Current alpha value
double PLC_GetCriticality();        // Current criticality score
double PLC_GetCascadeProb();        // Current cascade probability
int    PLC_GetCascadeDirection();   // Direction: +1 bull, -1 bear, 0 neutral
string PLC_GetRegime();             // Current market regime
string PLC_GetSignal();             // Current signal status
double PLC_GetRiskMultiplier();     // Recommended risk adjustment
double PLC_GetTPMultiplier();       // Recommended TP adjustment

📞 Support & Contributing

Issues

If you encounter bugs or have feature requests, please open an issue on GitHub.

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes with clear commit messages
  4. Submit a pull request

Code Style

  • Follow MQL5 naming conventions
  • Comment complex algorithms
  • Include input parameter descriptions
  • Test thoroughly before submitting

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Concepts based on research in econophysics and complexity science
  • Inspired by the work of Benoit Mandelbrot on fractal geometry in markets
  • Built on the MetaTrader 5 platform by MetaQuotes

📖 Further Reading

Academic Papers

  • Mandelbrot, B. (1963). "The Variation of Certain Speculative Prices"
  • Bak, P., Tang, C., & Wiesenfeld, K. (1987). "Self-organized criticality"
  • Gabaix, X. et al. (2003). "A theory of power-law distributions in financial market fluctuations"

Books

  • "The (Mis)Behavior of Markets" by Benoit Mandelbrot
  • "How Nature Works: The Science of Self-Organized Criticality" by Per Bak
  • "Quantitative Trading" by Ernest Chan

Version: 1.0.0
Last Updated: November 2025
MQL5 Build: Compatible with MT5 build 3000+

For questions or support, please open an issue on GitHub or contact the repository maintainer.

Releases

No releases published

Packages

No packages published

Languages