Back to Community
How to manage stop-loss

Hey there. I have written a module to manage stop losses. It is modular and can be plugged into any existing algorithm to perform a trailing stop-loss exit. It works for long as well as for short positions.

Functionalities are:

  • identify any open positions and orders with no stop (short and long)
  • create new stop levels
  • manage existing stop levels
  • create StopOrders with appropriate price and amount

To use it, please

  1. Copy my code lines 54-156 into your algorithm,
  2. Add these three lines of code into your algorithm:
# into initialize  
context.SL_Manager = StopLoss_Manager()  
schedule_function(context.SL_Manager.manage_orders, date_rules.every_day(), time_rules.market_open())

# at the end of rebalance and wherever you create new orders  
context.SL_Manager.manage_orders(context, data)  

To demonstrate the functionality, my algorithm opens a long-position for SPY. If this was closed through stop-loss, it will wait 10 days to re-open that position.

Right now, this will for swing-trading but not for pairs-trading. But I am planing to add functionality to handle spread-positions.

Cheers, Sebastian

Clone Algorithm
Backtest from to with initial capital
Total Returns
Max Drawdown
Benchmark Returns
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 5870cc127cf762620dfe652d
There was a runtime error.
3 responses

This is awesome really solved a big problem for me thank you!

I'm getting an "attempt to place an order with a stop price of nan", any ideas?

Could be delisted, so add the can_trade() test, and/or could just be a bar with no trades so replace all 'close' with 'price' which is forward filled.

    for sec in self.stops.index:  
        if not data.can_trade(sec): continue