kernc / backtesting.py

:mag_right: :chart_with_upwards_trend: :snake: :moneybag: Backtest trading strategies in Python.
https://kernc.github.io/backtesting.py/
GNU Affero General Public License v3.0
5.33k stars 1.04k forks source link

increase the cash in successful trades #1163

Open C1ph3R-s opened 1 month ago

C1ph3R-s commented 1 month ago

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)
s-kust commented 1 month ago

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