backtesting.py icon indicating copy to clipboard operation
backtesting.py copied to clipboard

increase the cash in successful trades

Open C1ph3R-s opened this issue 1 year ago • 1 comments

Hi,

I would like to increase the cash by 0.25 for every successful trade. I tried something like this, but it hasn't worked yet. Do you have any suggestions?


# Subclass Backtest to modify cash after each successful trade
class CustomBacktest(Backtest):
    def _on_order(self, order):
        # Call the parent class's _on_order method to ensure all default behavior is preserved
        super()._on_order(order)
        
        # Check if the order is closed
        if order.is_closed:
            print(f"Order closed: {order}")  # Debugging: Print order details
            
            # Check if the closed order was profitable
            if order.pl > 0:
                print(f"Profitable order: {order.pl}")  # Debugging: Print order profit
                
                # Increase cash by 25% of the current cash balance
                original_cash = self._cash
                self._cash += self._cash * 0.25
                print(f"Cash updated from {original_cash} to {self._cash}")  # Debugging: Print cash update details

# Create a Backtest object with the strategy and the DataFrame
bt = CustomBacktest(dfpl, MyStrat, cash=100, margin=1/10, commission=0.00)

C1ph3R-s avatar Aug 06 '24 09:08 C1ph3R-s

Strategy has a list of closed trades. Try something like this:

if self.closed_trades[-1].pl > 0:
    self._broker._cash += self._broker._cash * 0.25

s-kust avatar Aug 14 '24 04:08 s-kust

You could also maybe use negative fixed commissions from https://github.com/kernc/backtesting.py/commit/8fbb902a8cf45280078745dbb02a7e3ae01f2293#diff-116e378d79600fdb62391576c1d6adc7f6f5c7fbcab1ceaca103178fc1f68559R1092 (should be released shortly).

kernc avatar Feb 01 '25 15:02 kernc