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.
Why PyEventBT?
Section titled “Why PyEventBT?”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.
Key Benefits
Section titled “Key Benefits”- 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).
How It Works
Section titled “How It Works”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.
- Market Data arrives as
BarEventobjects (OHLCV + Spread bars) - Your Strategy processes the data and generates
SignalEventobjects - Position Sizing calculates how much to trade
- Risk Engine validates the trade against your risk rules
- Execution Engine places the order (simulated or real)
- 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.
Events
Section titled “Events”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
Modules
Section titled “Modules”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.
Code Reusability
Section titled “Code Reusability”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
Developer Experience
Section titled “Developer Experience”The framework prioritizes ease of use without sacrificing power:
- Simple API: High-level
Strategyclass 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
Author’s Motivation
Section titled “Author’s Motivation”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.
The Problem
Section titled “The Problem”Most backtesting frameworks suffer from one or more of these issues:
- Look-Ahead Bias: Vectorized backtesting can inadvertently use future data
- Unrealistic Execution: Assumptions about fills, slippage, and timing don’t match reality
- Backtest/Live Divergence: Code that works in backtests fails in live trading
- Limited Flexibility: Hard to customize risk management, sizing, or execution logic
- Complex Setup: Difficult to integrate with live trading platforms
The Solution
Section titled “The Solution”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 Vision
Section titled “The Vision”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
Architecture
Section titled “Architecture”Key Components
Section titled “Key Components”Strategy
Section titled “Strategy”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
Trading Director
Section titled “Trading Director”The orchestrator that:
- Manages the event loop
- Routes events to appropriate handlers
- Coordinates all system components
- Handles both backtest and live trading sessions
Signal Engine
Section titled “Signal Engine”Executes your strategy logic:
- Receives BarEvents
- Calls your strategy function
- Returns SignalEvents
Portfolio Handler
Section titled “Portfolio Handler”Orchestrates the order generation pipeline:
- Receives SignalEvents
- Coordinates Sizing Engine and Risk Engine
- Creates OrderEvents
Sizing Engine
Section titled “Sizing Engine”Calculates position sizes based on:
- Available capital
- Risk parameters
- Account equity
- Custom sizing rules
Risk Engine
Section titled “Risk Engine”Validates orders against risk rules:
- Maximum position size
- Exposure limits
- Correlation rules
- Custom risk constraints
Execution Engine
Section titled “Execution Engine”Handles order execution:
- Processes OrderEvents
- Interfaces with brokers (MT5 simulator or live)
- Generates FillEvents
- Manages stop-loss and take-profit
Portfolio
Section titled “Portfolio”Tracks account state:
- Open positions
- Pending orders
- Account balance and equity
- Trade history
Data Provider
Section titled “Data Provider”Manages market data:
- Historical data from CSV files
- Live data from MT5
- Multi-timeframe support
- Bar and tick data access
Trading Context
Section titled “Trading Context”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.
Extensibility
Section titled “Extensibility”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
Integration Points
Section titled “Integration Points”- 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