I want to develop a trading strategy in python, to test it with the help of backtrader.
my strategy should track position loss value in points and open reverse stop position on specific threshold (for example -5000points of current position). I like the script to work on a minute chart timeframe.
I want the strategy to run intraday, within a specific timeframe (for example starting on 01:15 each day and stopping on 21:00).
On starting time the strategy should start with a loops. Aim of the loop is to open a reverse stop order with an increased lotsize (lotsize of related order * multiplier) everytime the related order hits the loss threshold.
On stopping time, the script should end up all tasks and close all active positions and go into sleep until next starting time.
The loop in detail should go like this (you already mentioned it pretty right in your previous answer) (additional info: I need to be able to change the parameters as easy as possible. Perhaps it would be best to make them accessible in a separate code file. In general I’m a very big fan of modular coding style. Everytime I use X in the following explanation I want a parameter):
on first time starting the loop it should open a market order in X Direction (BUY or SELL) with LotSize of X (default value 0.01). Than the Strategy should keep go on working like you mentioned in point 1-4 of your previous answer:
It should start tracking the loss of this position like you mentioned in point 1 of your previous answer. It should check as frequently as possible the entered Threshold of loss in points (X, default value is -5000points).
If the threshold is touched for the first time, a reverse stop market order should be opened with increased lotsize (calculated: lotsize original related order * multiplier (X = 5.0).
The old order should be closed.
The loop should restart: tracking the loss touching the threshold, closing and opening another reverse stop position with increased lotsize again.
The loop should getting repeated maximum X times (Parameter for MaxLoopCount, default value should be 5).
please do an outline and implement this strategy ready for usage within backtrader right away.
Assistant
I want to develop a trading strategy in python, to test it… · The Chat Archive
Certainly! Below is a modular Python implementation of your trading strategy using Backtrader. The code is organized into separate files to enhance readability and maintainability. Here's an overview of the structure:
config.py: Contains all the configurable parameters.
strategy.py: Defines the trading strategy based on your specifications.
main.py: Sets up the Backtrader environment, loads the data, and runs the backtest.
1. config.py
This file holds all the parameters, making it easy to modify them without altering the core strategy code.
python
# config.py
# Trading Parameters
TRADING_DIRECTION = 'BUY' # 'BUY' or 'SELL'
INITIAL_LOTSIZE = 0.01 # Initial lot size
LOSS_THRESHOLD_POINTS = -5000 # Loss threshold in points
MULTIPLIER = 5.0 # Lot size multiplier
MAX_LOOP_COUNT = 5 # Maximum number of loops
# Time Parameters
START_TIME = '01:15' # Strategy start time (HH:MM)
STOP_TIME = '21:00' # Strategy stop time (HH:MM)
# Data Parameters
DATA_FILE = 'path_to_your_data.csv' # Path to your CSV data file
TIMEFRAME = 'M1' # Timeframe (e.g., 'M1' for 1-minute)
# Backtrader Parameters
CEREBRO_CAPITAL = 100000 # Starting capital
2. strategy.py
This file contains the strategy logic. It tracks the position loss and manages reversing positions when the loss threshold is hit.
python
# strategy.py
import backtrader as bt
from datetime import time
import config
class ReverseStopStrategy(bt.Strategy):
params = (
('direction', config.TRADING_DIRECTION),
('initial_lotsize', config.INITIAL_LOTSIZE),
('loss_threshold', config.LOSS_THRESHOLD_POINTS),
('multiplier', config.MULTIPLIER),
('max_loop_count', config.MAX_LOOP_COUNT),
('start_time', config.START_TIME),
('stop_time', config.STOP_TIME),
)
def __init__(self):
self.order = None
self.current_lotsize = self.p.initial_lotsize
self.loop_count = 0
self.position_entry_price = 0
self.in_trading_period = False
def log(self, txt, dt=None):
""" Logging function """
dt = dt or self.datas[0].datetime.datetime(0)
print(f'{dt} - {txt}')
def start_trading_period(self):
self.in_trading_period = True
self.loop_count = 0
self.current_lotsize = self.p.initial_lotsize
self.log('Starting trading period.')
self.open_initial_order()
def stop_trading_period(self):
self.in_trading_period = False
self.log('Stopping trading period. Closing all positions.')
if self.position:
self.close()
def open_initial_order(self):
if self.p.direction.upper() == 'BUY':
self.order = self.buy(size=self.current_lotsize)
self.log(f'Opened BUY order with size {self.current_lotsize}')
elif self.p.direction.upper() == 'SELL':
self.order = self.sell(size=self.current_lotsize)
self.log(f'Opened SELL order with size {self.current_lotsize}')
else:
raise ValueError("Direction must be 'BUY' or 'SELL'")
def next(self):
current_time = self.datas[0].datetime.time(0)
# Convert string time to datetime.time
start_hour, start_minute = map(int, self.p.start_time.split(':'))
stop_hour, stop_minute = map(int, self.p.stop_time.split(':'))
start = time(start_hour, start_minute)
stop = time(stop_hour, stop_minute)
if start <= current_time <= stop:
if not self.in_trading_period:
self.start_trading_period()
if self.position:
# Calculate loss in points
if self.p.direction.upper() == 'BUY':
loss = self.data.close[0] - self.position.price
else:
loss = self.position.price - self.data.close[0]
self.log(f'Current loss: {loss} points')
if loss <= self.p.loss_threshold and self.loop_count < self.p.max_loop_count:
self.log(f'Loss threshold reached: {loss} <= {self.p.loss_threshold}')
self.reverse_position()
else:
if self.in_trading_period:
self.stop_trading_period()
def reverse_position(self):
# Close current position
self.log('Closing current position.')
self.close()
# Increase lot size
self.current_lotsize *= self.p.multiplier
self.loop_count += 1
self.log(f'Loop count: {self.loop_count}. New lot size: {self.current_lotsize}')
# Open reverse order
if self.p.direction.upper() == 'BUY':
self.order = self.sell(size=self.current_lotsize)
self.log(f'Opened SELL order with size {self.current_lotsize}')
else:
self.order = self.buy(size=self.current_lotsize)
self.log(f'Opened BUY order with size {self.current_lotsize}')
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
# Order is submitted/accepted to/by broker - Nothing to do
return
if order.status in [order.Completed]:
if order.isbuy():
self.log(f'BUY EXECUTED, Price: {order.executed.price}, Size: {order.executed.size}')
elif order.issell():
self.log(f'SELL EXECUTED, Price: {order.executed.price}, Size: {order.executed.size}')
self.order = None
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('Order Canceled/Margin/Rejected')
self.order = None
def notify_trade(self, trade):
if not trade.isclosed:
return
self.log(f'TRADE PROFIT, GROSS: {trade.pnl}, NET: {trade.pnlcomm}')
3. main.py
This script sets up the Backtrader environment, loads the data, adds the strategy, and runs the backtest.
python
# main.py
import backtrader as bt
import config
from strategy import ReverseStopStrategy
import pandas as pd
from datetime import datetime
def run_backtest():
cerebro = bt.Cerebro()
# Add strategy
cerebro.addstrategy(ReverseStopStrategy)
# Set initial capital
cerebro.broker.setcash(config.CEREBRO_CAPITAL)
# Set commission (optional)
cerebro.broker.setcommission(commission=0.0001)
# Load data
data = bt.feeds.GenericCSVData(
dataname=config.DATA_FILE,
dtformat='%Y-%m-%d %H:%M:%S',
timeframe=bt.TimeFrame.Minutes,
compression=1,
datetime=0,
open=1,
high=2,
low=3,
close=4,
volume=5,
openinterest=-1,
# Adjust these if your CSV has headers or different formats
)
cerebro.adddata(data)
# Print starting cash
print(f'Starting Portfolio Value: {cerebro.broker.getvalue()}')
# Run backtest
cerebro.run()
# Print final cash
print(f'Final Portfolio Value: {cerebro.broker.getvalue()}')
# Plot results (optional)
cerebro.plot()
if __name__ == '__main__':
run_backtest()
The strategy starts monitoring at the specified START_TIME and stops at STOP_TIME each trading day.
At the start time, it places an initial market order in the specified direction (BUY or SELL) with the initial lot size.
Monitoring:
Continuously monitors the loss in points relative to the entry price.
If the loss exceeds the LOSS_THRESHOLD_POINTS, it closes the current position and opens a reverse position with an increased lot size (current_lotsize * MULTIPLIER).
Loop Control:
This loop can repeat up to MAX_LOOP_COUNT times within the trading period.
After reaching the maximum loop count or end of the trading period, all positions are closed, and the strategy waits until the next trading day.
Navigate to your project directory in the terminal and run:
bash
python main.py
This will execute the backtest based on your strategy and display the portfolio values before and after the test. Additionally, it will plot the trading performance if you have a graphical backend available.
7. Customization
All key parameters are defined in config.py. To modify the strategy, simply update the relevant values in this file. For example:
Point Calculation: In this implementation, a "point" is considered as a single unit movement in price. Ensure that this aligns with your asset's pricing (e.g., for Forex, you might need to adjust the point definition based on pips).
Data Frequency: The strategy is set to work on a 1-minute (M1) timeframe. Ensure your data matches this frequency or adjust the TIMEFRAME and compression parameters accordingly.
Error Handling: The strategy includes basic error handling for order submissions. You might want to enhance it based on specific requirements or broker constraints.
Testing: Before deploying this strategy live, thoroughly backtest it with historical data and consider running it in a paper trading environment to verify its behavior.
Feel free to reach out if you have any questions or need further assistance!