Building a Trading Backtesting System — Part 5: Implementing flexible and reusable strategies

Xavier Escudero
2 min readMar 7, 2024
Image generated with Leonardo.AI

I found myself relying on Backtrader as is, but I noticed a recurring pattern of boilerplate code and duplication every time I created a new strategy.

For each instrument we can summarize a common process:

  • Assess the current position.
  • If no position is open, evaluate whether the entry condition is met, and initiate a long or short position accordingly.
  • If a position is open, examine whether an exit condition is present to close the position.
Common process of Backtesting

Base strategy

After discovering an enlightening article authored by Esteban Thilliez titled Build a Trading Bot with Python — 3. Strategies Templates, I was inspired to refactor my code in a similar fashion.

I adapted the approach to accommodate multiple instruments rather than just a single one, abstracting indicators and additional functionalities to suit my specific needs.

The code is shown below:

--

--

Xavier Escudero

Innovation enthusiast, passionate about automation in several fields, like software testing and trading bots