From 0dca328a9ef73338f0ea60c04c93ad13538ceb5e Mon Sep 17 00:00:00 2001 From: "Bobby (aider)" Date: Thu, 13 Feb 2025 23:42:00 -0800 Subject: [PATCH] refactor: Improve stop loss handling with error resilience and position size check --- src/pages/backtesting/backtesting_page.py | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) 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