diff --git a/src/pages/backtesting/backtesting_page.py b/src/pages/backtesting/backtesting_page.py index b33aefd..8a879ce 100644 --- a/src/pages/backtesting/backtesting_page.py +++ b/src/pages/backtesting/backtesting_page.py @@ -100,16 +100,19 @@ class DynamicStrategy(Strategy): price = self.data.Close[-1] # Check stop loss for existing position - if self.position: - # Calculate the percentage loss from entry - entry_price = self.position.entry_price # Changed from entry_price() to entry_price - current_loss = ((price - entry_price) / entry_price) * 100 - - # If loss exceeds 7%, close the position - if current_loss < -7: - print(f"Stop loss triggered - Loss: {current_loss:.2f}%") - self.position.close() - return # Exit the method to prevent new entries on the same candle + if self.position and self.position.size > 0: # Make sure we have an active position + try: + # Calculate the percentage loss from entry + entry_price = self.position.entry_price # Access as property + current_loss = ((price - entry_price) / entry_price) * 100 + + # If loss exceeds 7%, close the position + if current_loss < -7: + print(f"Stop loss triggered - Loss: {current_loss:.2f}%") + self.position.close() + return # Exit the method to prevent new entries on the same candle + except AttributeError as e: + print(f"Warning: Could not check stop loss - {str(e)}") # Debug current price and position if len(self.data.Close) % 20 == 0: # Log every 20th candle to avoid spam