Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Event Driven Backtesting and Event Loops for Traders

9 min read

Event driven backtesting tests a strategy by replaying history one event at a time (a new bar or tick, then the signal it causes, the order, the fill and the portfolio update) inside an event loop. Because the strategy only ever sees data that has already arrived, it avoids look-ahead bias and can model slippage, partial fills and costs the way a live system meets them, at the price of running slower than a vectorized backtest.

If you have ever built or tested a trading strategy, you have probably come across two approaches. Vectorized backtesting and event driven backtesting.

At first, they may seem similar. Both aim to test strategies on historical data. But under the hood, they work very differently.

Build desktop apps with Claude Code
LIVE COURSE · DEC 2026

Build desktop apps with Claude Code

Plan, build, package and distribute desktop apps for Windows, macOS and Linux, with Claude Code as your development partner.

  • 5 live sessions, 10 hours, starts 7 December 2026
  • CRM, algo trading and NSE Bhavcopy projects
  • Installers for Windows, macOS and Linux
Join the course →by Marketcalls

This article simplifies event driven backtesting and explains why it matters for traders.

Key takeaways
  • An event loop takes the next event from a queue, processes it, and adds any new events that it triggers.
  • Typical events: market data, signal, order, fill (execution) and portfolio update.
  • Event driven does not mean tick data: daily or one minute bars work just as well.
  • It is slower than vectorized backtesting but closer to live trading, and the same code can run live.
  • Use vectorized tools to explore ideas quickly, and event driven to validate the ones that survive.

What is an Event Loop in Trading

An event loop is a system that processes things one at a time in sequence.

In trading, the system reacts to events such as:

  • New market data arrives
  • A signal is generated
  • An order is placed
  • An order gets filled

Each of these is an event.

The loop continuously waits for the next event and processes it step by step.

This mirrors how real markets operate. Everything happens in a sequence, not all at once.


Types of Events in Event Driven Backtesting

Event driven systems are built around different categories of events.

Market Data Events

New tick or candle data arrives

Signal Events

Your strategy generates buy or sell decisions

Order Events

Orders are created and sent to the broker

Execution Events

Orders get filled, partially filled, or rejected

Order Update Events

Orders are modified, cancelled, or updated after partial fills

Portfolio Events

Positions, cash, and profit and loss are updated


How Event Driven Backtesting Works

Event driven backtesting simulates real world flow step by step.

Simple loop:

  1. Market data event
  2. Signal event
  3. Order event
  4. Execution event
  5. Portfolio update

Then repeat.

Step through
Watch an event loop process six bars

Click to process one event at a time and see how market, signal, order and fill events move through the queue.

Event queue
Portfolio
Event log

    Rule used: buy 100 shares when the close is above ₹101, sell when it falls below ₹99. Orders fill at the next bar’s open, so the fill price is never the same as the signal bar’s close.


    Does Event Driven Mean Tick Data Only

    No.

    Event driven backtesting works with:

    • Tick data
    • One minute data
    • Hourly data
    • Daily data

    Each data point becomes an event.

    Tick data is not mandatory. It only becomes important for very high precision strategies.


    Why This Matters

    Real trading is not instant.

    Orders can be:

    • Partially filled
    • Delayed
    • Modified
    • Cancelled

    Event driven systems capture all of this.


    Coming from Vectorized Tools like Amibroker and TradingView

    If you are used to tools like AmiBroker or TradingView, this shift can feel very different.

    Here are the key things to understand:

    1. Bar by Bar Execution

    You no longer compute on full arrays. Each bar is processed one at a time. The system only knows the past and present.


    2. No Look Ahead Bias by Design

    Future data does not exist yet. This makes your backtest naturally safer from accidental mistakes.


    3. The Core Loop is an Event Queue

    Everything flows through a sequence:

    MarketEvent, then SignalEvent, then OrderEvent, then FillEvent

    Each event triggers the next.


    4. Realistic Order Simulation

    You can model:

    • Slippage
    • Partial fills
    • Different order types
    • Latency

    Vectorized tools often assume perfect fills.


    5. Portfolio State is Always Live

    At every step, your system tracks:

    • Equity
    • Open positions
    • Available capital

    This allows dynamic position sizing.


    6. It is Much Slower

    Vectorized backtests run extremely fast.

    Event driven systems process each step, so they take more time, especially in Python.


    7. Costs are Easier to Model

    You can inject costs at execution level:

    • Brokerage
    • Taxes
    • Exchange fees
    • Impact cost

    This gives more control than global settings.


    8. Multi Asset Logic is Natural

    Since state is updated continuously, you can easily implement:

    • Pairs trading
    • Hedging
    • Cross asset signals

    9. Easier Transition to Live Trading

    The same system can be connected to live data.

    You replace historical data with live feed, and the logic stays the same.


    10. Libraries to Explore

    Good starting points:

    • Backtrader: Mature and widely used. Note that the last release on PyPI (1.9.78.123) dates from April 2023, so it is stable but no longer actively developed.
    • bt: Simple and useful for learning
    • Nautilus Trader: High performance and modern, with frequent releases (version 1.231.0 in August 2026). Our Nautilus Trader Part 1 tutorial shows event driven backtesting with OpenAlgo data.

    You can also explore QuantConnect LEAN for a production grade engine.


    Event driven backtesting in Python: a minimal example

    The easiest way to understand the idea is to write a tiny engine yourself. The code below has four parts: a strategy that reacts to market events, a portfolio that turns signals into sized orders, a simulated broker that fills orders at the next bar’s open with slippage and costs, and the loop that drains the event queue after every bar. It uses only the Python standard library.

    from collections import deque
    from dataclasses import dataclass
    
    
    @dataclass
    class MarketEvent:
        bar: dict          # one OHLC bar: {"time", "open", "high", "low", "close"}
    
    @dataclass
    class SignalEvent:
        side: str          # "BUY" or "SELL"
    
    @dataclass
    class OrderEvent:
        side: str
        qty: int
    
    @dataclass
    class FillEvent:
        side: str
        qty: int
        price: float
        cost: float
    
    
    class Strategy:
        """Simple moving average crossover. It only ever sees bars that already happened."""
        def __init__(self, fast=5, slow=20):
            self.fast, self.slow, self.closes, self.in_market = fast, slow, [], False
    
        def on_market(self, ev, queue):
            self.closes.append(ev.bar["close"])
            if len(self.closes) < self.slow:
                return
            f = sum(self.closes[-self.fast:]) / self.fast
            s = sum(self.closes[-self.slow:]) / self.slow
            if f > s and not self.in_market:
                queue.append(SignalEvent("BUY")); self.in_market = True
            elif f < s and self.in_market:
                queue.append(SignalEvent("SELL")); self.in_market = False
    
    
    class Portfolio:
        def __init__(self, cash=100000.0):
            self.cash, self.qty = cash, 0
    
        def on_signal(self, ev, queue, last_close):
            if ev.side == "BUY":
                qty = int(self.cash * 0.95 // last_close)   # size from live cash
            else:
                qty = self.qty
            if qty > 0:
                queue.append(OrderEvent(ev.side, qty))
    
        def on_fill(self, ev):
            sign = 1 if ev.side == "BUY" else -1
            self.qty += sign * ev.qty
            self.cash -= sign * ev.qty * ev.price + ev.cost
    
    
    class SimulatedBroker:
        """Fills market orders at the NEXT bar's open plus slippage, like a real order would."""
        def __init__(self, slippage_pct=0.0005, cost_pct=0.0003):
            self.pending, self.slip, self.cost = [], slippage_pct, cost_pct
    
        def on_order(self, ev):
            self.pending.append(ev)
    
        def on_market(self, ev, queue):
            for o in self.pending:
                px = ev.bar["open"] * (1 + self.slip if o.side == "BUY" else 1 - self.slip)
                queue.append(FillEvent(o.side, o.qty, px, px * o.qty * self.cost))
            self.pending = []
    
    
    def run_backtest(bars):
        queue = deque()
        strategy, portfolio, broker = Strategy(), Portfolio(), SimulatedBroker()
        for bar in bars:                       # the outer loop: one market event per bar
            queue.append(MarketEvent(bar))
            while queue:                       # the event loop: drain everything this bar caused
                ev = queue.popleft()
                if isinstance(ev, MarketEvent):
                    broker.on_market(ev, queue)     # fill yesterday's orders at today's open
                    strategy.on_market(ev, queue)
                elif isinstance(ev, SignalEvent):
                    portfolio.on_signal(ev, queue, bar["close"])
                elif isinstance(ev, OrderEvent):
                    broker.on_order(ev)
                elif isinstance(ev, FillEvent):
                    portfolio.on_fill(ev)
                    print(f'{bar["time"]} {ev.side} {ev.qty} @ {ev.price:.2f}')
        equity = portfolio.cash + portfolio.qty * bars[-1]["close"]
        print(f"Final equity: {equity:,.2f}")
        return equity
    

    Feed run_backtest() a list of bars (for example from your broker API or a CSV file, each bar a dict with time, open, high, low and close) and it prints every fill and the final equity. Notice the order of calls on each market event: the broker fills yesterday’s orders before the strategy looks at today’s bar. That single detail is what keeps the backtest honest.

    Vectorized vs event driven backtesting at a glance

    VectorizedEvent driven
    How it runsWhole arrays at once (NumPy, pandas)One event at a time in a loop
    SpeedVery fast; thousands of parameter sets in secondsSlower, especially in pure Python
    Look-ahead biasEasy to introduce by accident (shift mistakes)Prevented by design
    Fills and costsUsually assumed at close or next openSlippage, partial fills, order types, latency
    Position sizingFixed rulesDynamic, from live cash and equity
    Path to live tradingUsually rewrittenSame code with a live data feed
    ExamplesAmiBroker, TradingView, VectorBTBacktrader, Nautilus Trader, QuantConnect LEAN

    For a fuller comparison with examples, read event driven backtesting vs vectorized backtesting, and for the bias that event driven engines protect you from, see understanding look-ahead bias.

    Why Event Driven Backtesting is Slower

    Event driven systems simulate each step in time.

    For every time step:

    • State is updated
    • Events are processed
    • Orders are simulated

    This creates many small operations.

    Vectorized systems process everything at once using optimized math libraries.

    So:

    • Vectorized backtesting is fast because it simplifies reality
    • Event driven backtesting is slower because it simulates reality

    When Should You Use Event Driven Backtesting

    Use event driven when:

    • Execution matters
    • Strategy depends on timing
    • You want realistic results

    Use vectorized when:

    • You need speed
    • You are exploring ideas

    Most traders use both.


    Final Thoughts

    Event driven backtesting is about simulating the full trading lifecycle.

    From data to signal to order to execution.

    It is not about tick data. It is about sequence and realism.

    If you want to move closer to real trading conditions, this approach is essential.

    Common mistakes in event driven backtests

    • Filling at the signal bar’s close. If the signal needs the close, the earliest realistic fill is the next bar. Fill there, with slippage.
    • Letting the strategy read the portfolio before fills arrive. Process fill events before generating new signals, or position checks will be one bar out of date.
    • Ignoring market hours and holidays. An order generated after the last bar of the day should not fill at a price from the same evening.
    • Comparing results with a vectorized test without matching the fill rules. Differences often come from execution assumptions, not from bugs.

    Frequently Asked Questions

    What is event driven backtesting?

    It is a backtesting method that processes historical data as a sequence of events (bars or ticks) and passes each one through the same components a live system uses: strategy, portfolio, order handling and execution. The strategy only knows data up to the current event.

    Is Backtrader event driven?

    Yes. Backtrader calls your strategy’s next() method once per bar and simulates order execution through its broker, which makes it event driven. Its last PyPI release was in April 2023.

    Is event driven backtesting better than vectorized backtesting?

    Neither is better in every case. Vectorized is far faster for research and parameter sweeps; event driven is more realistic for execution, sizing and multi asset logic. Most traders use both.

    Which Python library is best for event driven backtesting?

    For learning, Backtrader has the most tutorials. For speed and a path to live trading, Nautilus Trader is a strong modern option. QuantConnect LEAN suits traders who want a hosted, production grade engine.

    Python Elite membership

    MEMBERSHIP

    Python Elite membership

    15 Python, AI and algo trading programs in one plan, including QuantFlow and AI Bootcamp live mentorship.

    • Python from fundamentals to trading apps
    • Backtesting, broker APIs and OpenAlgo
    • Live QuantFlow and AI Bootcamp sessions
    View Python Elite →by Marketcalls

    Learn by watching: free videos every week

    Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

    Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

    Leave a Reply

    Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More