refactor: Improve stop loss handling with error resilience and position size check

This commit is contained in:
Bobby (aider) 2025-02-13 23:42:00 -08:00
parent c771e479bb
commit 0dca328a9e

View File

@ -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 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
# 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