Member-only story
Building a Trading Backtesting System — Part 5: Implementing flexible and reusable strategies
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.
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: