Skip to content

PyEventBT - Event-Driven Backtesting and Live Trading with Python and MetaTrader 5

PyEventBT is an institutional-grade event-driven backtesting and live trading framework built with Python for the MetaTrader 5 platform.

It provides a complete mock of the MT5 API for an easy transition between backtesting and live trading, allowing traders to easily develop multi-rule, multi-timeframe and multi-instrument strategies.

Whether you’re building simple moving average crossovers or complex multi-rule and multi-timeframe strategies, PyEventBT provides the tools you need to develop, test, and deploy with confidence.

Its modular architecture allows you to design your own signal sources, position sizing logic and risk management overlay as independent and interchangeable blocks.

PyEventBT helps traders develop, test and deploy algorithmic trading strategies with ease. It provides a unified ecosystem where you can backtest and live trade your strategies with the same code base, minimizing the impact of errors when moving from backtesting to live trading.

It also means you won’t need to write a single line of MQL5 code or depend on the MetaTrader Backtester anymore, as PyEventBT allows you to completely bypass it and only use the MetaTrader 5 platform to send the live trades once your strategy is ready.

Even this event-driven approach is generally slower than vectorized backtesting, it ensures that your backtest results accurately reflect how your strategy would have performed in production.

  • Easy to Use Modules: Simple API with decorator-based strategy definition and pluggable components for risk management, position sizing and execution let you customize every aspect of your trading system.
  • Python, not MQL5: You can use the full power of Python to develop your strategies, without the need to write a single line of MQL5 code.
  • Multi Timeframe-Instrument-Rule: Handle multiple timeframes, instruments and rules in a single strategy.
  • Write Once, Run Anywhere: The same strategy code runs in both backtesting and live trading. No need to rewrite or adapt your logic when moving from research to production.
  • Production-Ready: Built-in integration with MetaTrader 5 means you can deploy your strategies to live markets with minimal configuration.
  • Comprehensive Analysis: Built-in performance metrics and visualization tools let you analyze your backtest results and make informed decisions.
  • Technical Indicators: Built-in library of common indicators (ATR, SMA, EMA, RSI and more).

PyEventBT is built around a central events loop that processes events sequentially as they arrive. Those events are channeled through a FIFO Queue and different Modules, each one being responsible of processing a different type of event and decoupling the strategy logic from the rest of the system.

  1. Market Data arrives as BarEvent objects (OHLCV + Spread bars)
  2. Your Strategy processes the data and generates SignalEvent objects
  3. Position Sizing calculates how much to trade
  4. Risk Engine validates the trade against your risk rules
  5. Execution Engine places the order (simulated or real)
  6. Portfolio tracks positions, margins, P&L and account state

This flow ensures that your strategy only sees data that would have been available at that moment, just like in real trading.

Those events are:

  • BarEvent: Contains OHLCVS data for a time period
  • SignalEvent: Trading signal (BUY/SELL) from strategy
  • OrderEvent: Order to be executed (MARKET/LIMIT/STOP)
  • FillEvent: Confirmation of executed order
  • ScheduledEvent: Timer-based events for scheduled tasks

The framework follows a modular architecture where each component has a single, well-defined responsibility:

  • Signal Engine: Generates trading signals based on market data
  • Sizing Engine: Calculates appropriate position sizes
  • Risk Engine: Validates orders against risk management rules
  • Execution Engine: Handles order execution and broker communication
  • Portfolio: Tracks positions, orders, and account state
  • Data Provider: Manages market data access

This separation of concerns allows you to:

  • Swap components without affecting others (e.g., change risk rules without touching strategy logic)
  • Test components independently
  • Build custom implementations for any part of the system
  • Understand and reason about each part of your trading system

You can learn more about the different modules in the Modules guide.

PyEventBT is designed so that the same strategy code runs in both backtest and live trading. The framework abstracts away the differences between historical and real-time data, simulated and real execution, allowing you to:

  • Develop and test strategies using historical data
  • Deploy to live trading with minimal code changes
  • Have confidence that your backtest results will translate to live performance

The framework prioritizes ease of use without sacrificing power:

  • Simple API: High-level Strategy class handles complex orchestration
  • Decorator Pattern: Define strategies using intuitive decorators
  • Pythonic Design: Leverages Python’s strengths (type hints, dataclasses, etc.)
  • Comprehensive Documentation: Clear guides and examples for common use cases

PyEventBT was created by Marti Castany with the incredible help of Alain Porto and Jaume Antoli to address the limitations they encountered with existing backtesting frameworks.

It is also built on top of the ideas and work presented by M. Halls Moore in his blog QuantStart.

Most backtesting frameworks suffer from one or more of these issues:

  1. Look-Ahead Bias: Vectorized backtesting can inadvertently use future data
  2. Unrealistic Execution: Assumptions about fills, slippage, and timing don’t match reality
  3. Backtest/Live Divergence: Code that works in backtests fails in live trading
  4. Limited Flexibility: Hard to customize risk management, sizing, or execution logic
  5. Complex Setup: Difficult to integrate with live trading platforms

PyEventBT was designed to solve these problems by:

  • Event-Driven Processing: Eliminates look-ahead bias by processing events in chronological order
  • Realistic Simulation: Simulates actual broker behavior, including slippage and execution delays
  • Unified Codebase: Same strategy code for backtest and live trading
  • Modular Architecture: Easy to customize any component without affecting others
  • MT5 Integration: Direct connection to MetaTrader 5 for seamless live trading

The authors envisioned a framework that would:

  • Enable traders to develop strategies with confidence that backtest results reflect real performance
  • Provide a smooth path from research to production
  • Support both simple and complex trading strategies
  • Be extensible enough to accommodate custom requirements
  • Maintain high code quality and developer experience

The main entry point for users. Provides a high-level API for:

  • Defining strategy logic using decorators
  • Configuring risk and sizing engines
  • Running backtests
  • Deploying to live trading

The orchestrator that:

  • Manages the event loop
  • Routes events to appropriate handlers
  • Coordinates all system components
  • Handles both backtest and live trading sessions

Executes your strategy logic:

  • Receives BarEvents
  • Calls your strategy function
  • Returns SignalEvents

Orchestrates the order generation pipeline:

  • Receives SignalEvents
  • Coordinates Sizing Engine and Risk Engine
  • Creates OrderEvents

Calculates position sizes based on:

  • Available capital
  • Risk parameters
  • Account equity
  • Custom sizing rules

Validates orders against risk rules:

  • Maximum position size
  • Exposure limits
  • Correlation rules
  • Custom risk constraints

Handles order execution:

  • Processes OrderEvents
  • Interfaces with brokers (MT5 simulator or live)
  • Generates FillEvents
  • Manages stop-loss and take-profit

Tracks account state:

  • Open positions
  • Pending orders
  • Account balance and equity
  • Trade history

Manages market data:

  • Historical data from CSV files
  • Live data from MT5
  • Multi-timeframe support
  • Bar and tick data access

The framework maintains a TradingContext that indicates whether the system is running in:

  • BACKTEST: Historical data, simulated execution
  • LIVE: Real-time data, actual broker execution

Your strategy can check this context to adjust behavior if needed, though the framework is designed to work seamlessly in both modes.

Every major component has an interface that you can implement:

  • Custom Signal Engines: Define your own signal generation logic
  • Custom Sizing Engines: Implement custom position sizing algorithms
  • Custom Risk Engines: Create your own risk management rules
  • Custom Execution Engines: Integrate with other brokers or execution systems
  • Hooks: Add custom callbacks at various points in the event flow
  • MetaTrader 5: Full integration for backtesting and live trading
  • CSV Data: Import historical data from CSV files
  • Quantdle: Integration with Quantdle data services
  • Custom Brokers: Extensible architecture for other broker integrations