refactor: Improve stop loss handling with error resilience and position size check
This commit is contained in:
parent
c771e479bb
commit
0dca328a9e
@ -100,16 +100,19 @@ class DynamicStrategy(Strategy):
|
|||||||
price = self.data.Close[-1]
|
price = self.data.Close[-1]
|
||||||
|
|
||||||
# Check stop loss for existing position
|
# Check stop loss for existing position
|
||||||
if self.position:
|
if self.position and self.position.size > 0: # Make sure we have an active position
|
||||||
# Calculate the percentage loss from entry
|
try:
|
||||||
entry_price = self.position.entry_price # Changed from entry_price() to entry_price
|
# Calculate the percentage loss from entry
|
||||||
current_loss = ((price - entry_price) / entry_price) * 100
|
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:
|
# If loss exceeds 7%, close the position
|
||||||
print(f"Stop loss triggered - Loss: {current_loss:.2f}%")
|
if current_loss < -7:
|
||||||
self.position.close()
|
print(f"Stop loss triggered - Loss: {current_loss:.2f}%")
|
||||||
return # Exit the method to prevent new entries on the same candle
|
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
|
# Debug current price and position
|
||||||
if len(self.data.Close) % 20 == 0: # Log every 20th candle to avoid spam
|
if len(self.data.Close) % 20 == 0: # Log every 20th candle to avoid spam
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user