What is the correct pseudo-code order for event-based backtesting?
Hi,
I have what I think is a pretty simple question that I am getting caught in the technicalities of.
I am trying to develop an event-driven backtester using a simple loop without creating classes to specifically handle filling, orders, etc.
I am unsure about what order the loop should execute in and how to handle the edge cases.
Since my goal is to simulate somewhat-real execution, I intend to go as follows:
- Observe new event (new ohlcv bar for asset)
- Use this event + tracked event history to create a signal (buy, sell, or do nothing)
- "Send" the order based on this signal (if any)
- Execute at the start of the next bar using the next bar's open as our execution price
- Record things such as our portfolio's values, position changes, etc.
- Repeat 1
The problem I am running into is that I have seen that you should actually have the loop be something like:
- Observe new event (new ohlcv bar for asset)
- Execute our previously sent order (if any) using the opening price of the new bar
- Use this event + tracked event history to create a signal (buy, sell, or do nothing)
- "Send" the order based on this signal (if any)
- Record things such as our portfolio's values, position changes, etc.
- Repeat 1
to avoid optimistic execution/look-ahed bias.
I have seen that Interactive Brokers sumarizes an event-based framework as:
- Market Data Event: New bar or tick arrives (trade, quote, or bar close).
- Signal Event: Strategy logic consumes the market data and, if conditions match, emits a signal (e.g., “Buy 100 XYZ at market”).
- Order Event: Portfolio/Execution handler translates signals into orders (market, limit, stop), specifying type, size, and price.
- Fill Event: Broker simulator matches orders against market data (bid-ask, available volume) and issues partial/full fills at realistic prices.
- Update Event: Portfolio updates positions, cash, and risk metrics; may generate risk alarms (margin calls, forced liquidations).
- Performance Recording: Each fill triggers P&L calculations, slippage accounting, and is logged for performance analysis.
but I am still stuck on how exactly to translate this to loop pseudo code and whether we should use something like the first loop I have or maybe the second?
I am just looking for what is the best and cleanest way in a loop to handle sent orders in a simple testing framework..
Thanks!
Posted Apr 9, 2026, 7:55 PM UTC