@@ -451,6 +451,40 @@ def next(self):
451
451
trade .sl = min (trade .sl or np .inf ,
452
452
self .data .Close [index ] + self .__atr [index ] * self .__n_atr )
453
453
454
+ class PercentageTrailingStrategy (Strategy ):
455
+ """
456
+ A strategy with automatic trailing stop-loss, trailing the current
457
+ price at distance of some percentage. Call
458
+ `PercentageTrailingStrategy.set_trailing_sl()` to set said percentage
459
+ (`5` by default). See [tutorials] for usage examples.
460
+
461
+ [tutorials]: index.html#tutorials
462
+
463
+ Remember to call `super().init()` and `super().next()` in your
464
+ overridden methods.
465
+ """
466
+ _sl_percent = 5.
467
+ def init (self ):
468
+ super ().init ()
469
+
470
+ def set_trailing_sl (self , percentage : float = 5 ):
471
+ assert percentage > 0 , "percentage must be greater than 0"
472
+ """
473
+ Sets the future trailing stop-loss as some (`percentage`)
474
+ percentage away from the current price.
475
+ """
476
+ self ._sl_percent = percentage
477
+
478
+ def next (self ):
479
+ super ().next ()
480
+ index = len (self .data )- 1
481
+ for trade in self .trades :
482
+ if trade .is_long :
483
+ trade .sl = max (trade .sl or - np .inf ,
484
+ self .data .Close [index ]* (1 - (self ._sl_percent / 100 )))
485
+ else :
486
+ trade .sl = min (trade .sl or np .inf ,
487
+ self .data .Close [index ]* (1 + (self ._sl_percent / 100 )))
454
488
455
489
# Prevent pdoc3 documenting __init__ signature of Strategy subclasses
456
490
for cls in list (globals ().values ()):
0 commit comments