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