Implement stop loss



  • Hi, I'm learning Python in finance and now I'm stuck on implementing a stop loss strategy.
    Here is a code of next method , it seems to me excessive, so I suppose that there is a way to implement it better:

    As you can see the solution is not elegant and the results are irregular. When we are on the market and stop loss condition is met the stop loss strategy is not going on.
    I did read this blog post, but it didn't bright the light on.
    So, my question is how can I implement stop loss condition with backtrader?


  • administrators

    Except for the fact that you seem to have no direct entry point for long operations (because it is under stop loss condition, which should be negated), the code seems to cover what you want.

    The question would be what is what you consider to be irregular?



  • @backtrader said in Implement stop loss:

    Except for the fact that you seem to have no direct entry point for long operations (because it is under stop loss condition, which should be negated), the code seems to cover what you want.

    The question would be what is what you consider to be irregular?

    I have a test data with the results (buy dates, sell, stop loss). Buy dates are fine, but sell dates and stop loss are does not match.
    The biggest problem to me is to implement the following:
    If stop loss condition is met, sell assets immediately.


  • administrators

    @Антон-Козловский said in Implement stop loss:

    If stop loss condition is met, sell assets immediately.

    @Антон-Козловский said in Implement stop loss:

     self.order = self.sell(limit=self.dataclose[0]-2*self.atr[0], exectype=bt.Order.Limit) # sell assets for "buy price - 2*atr"
    

    A Limit will NOT be executed immediately. Only when the requested limit price can be matched.


  • administrators



  • Here is the link on the implementation of the trailing stop - Trailing stop
    Also you can use bracket orders in order to simulate it.

    The idea is that every time you open the trade you issue the stop order with certain price level without any additional conditions. If you want to have a trailing stop, then on each next() you cancel previous stop order and issue new one. Backtrader will decide if the order executed or not by itself, no need to check it.



  • @backtrader said in Implement stop loss:

    See: Docs - Order Management and Execution

    Thanks, I've got that by default orders cannot be executed immediately.

    @ab_trader said in Implement stop loss:

    Here is the link on the implementation of the trailing stop - Trailing stop
    Also you can use bracket orders in order to simulate it.

    The idea is that every time you open the trade you issue the stop order with certain price level without any additional conditions. If you want to have a trailing stop, then on each next() you cancel previous stop order and issue new one. Backtrader will decide if the order executed or not by itself, no need to check it.

    Thank you, could you, please, clarify the idea for such a dummy? :)
    I can't get the idea of creating a Stop order and canceling it. Could you please explain in details?
    For example, the stoploss conition is the lowest price of the day is lower than buy price, how it can be implemented?



  • How do you trade in real life using stop orders?


  • administrators

    @Антон-Козловский said in Implement stop loss:

    Thanks, I've got that by default orders cannot be executed immediately.

    Market orders are executed with the next incoming price, effective: *immediately

    @Антон-Козловский said in Implement stop loss:

    For example, the stoploss conition is the lowest price of the day is lower than buy price, how it can be implemented?

    if self.data.low < self.buy_price:  # buy_price was stored in notify_order from order.executed.price
        self.order = self.sell()  # we assume we were in a long position
    

    A couple of messages above you said your problem was the immediate execution of the stop-loss order, being the execution also different from the regular sell orders you were sending. The difference as explained above, but here again for reference:

    • You are issuing normal sell orders with: self.sell(), which by default issues a Market order which will be executed as soon as possible and with the market price

    • You are issuing stop-loss orders with: self.sell(exectype=bt.Order.Limit, price=x), which is a Limit order requesting to be matched at price=x or even at a best price if possible. But if the price moves against the order, it may be executed later or it may in fact never execute.



  • Thanks for your help. I think the problem is that I'm neglecting of learning the basic principles of the trading.



  • How can be implemented the following condition?
    Set stop-loss price at buy_price - 2 * ATR if the lowest price of the day is lower than buy_price - 2 * ATR.
    I assume, that a StopLimit order is not what I want, but after reading the docs for a few times the execution of each of them is still not clear to me.


  • administrators

    A StopLimit order doesn't know that you want to dynamically change the price following the ATR. There are two things here

    • Trigger price. That's for sure your buy_price - 2 * ATR
    • Execution price. That fully depends on the order type chosen. Two examples:
      • Market: the next available price will be used
      • Limit: you set the price. Which can be the Trigger price or one which is different (some ticks away from it)
        But in this case as explained above, execution may happen or not. Execution may happen even at a better price if your order faces an opening gap in your favor. But it may never happen if the price moves away from your order.

    The point is that you cannot for sure ensure that your Stop-Loss order will be executed unless you use Market and in this case you can control the Trigger price but not the Execution price.

    @Антон-Козловский said in Implement stop loss:

    if self.datalow[0] < (self.dataclose[0] - 2 * self.atr_buy): # stoploss condition
    

    But in any case. You don't use the buy_price for the stop-loss condition. You use the close.

    self.atr_buy = None # save atr at buy time
    

    In most cases the ATR used for dynamic stop-losses is not the ATR which was there at buy time, but the current ATR. Of course it if works for you ...



  • Thanks.
    So, except that there is no 100% confidence that the stoploss order will be executed the code is right?

    @backtrader said in Implement stop loss:

    But in any case. You don't use the buy_price for the stop-loss condition. You use the close.

    Yes, I know that, because I can't get the next opening price I'm using the current close price.

    @backtrader said in Implement stop loss:

    In most cases the ATR used for dynamic stop-losses is not the ATR which was there at buy time, but the current ATR. Of course it if works for you ...

    This is a condition I have, so this is should be so.


  • administrators

    @Антон-Козловский said in Implement stop loss:

    So, except that there is no 100% confidence that the stoploss order will be executed the code is right?

    Seems right. But only testing can say.

    @Антон-Козловский said in Implement stop loss:

    Yes, I know that, because I can't get the next opening price I'm using the current close price.

    But you stated above you wanted to use the buy_price



  • @backtrader

    @backtrader said in Implement stop loss:

    But you stated above you wanted to use the buy_price

    If I got right the buy price is an open price of the next bar. Since I have no access to the next bar in the current iteration I'm using the current close price.


  • administrators

    No, under buy_price, because your are talking about stop-loss (you are in the market), people will understand the price at which you bought your asset and not the expected (and yet unknown) price at which the next order, the stop-loss one will execute.



  • @backtrader said in Implement stop loss:

    No, under buy_price, because your are talking about stop-loss (you are in the market), people will understand the price at which you bought your asset and not the expected (and yet unknown) price at which the next order, the stop-loss one will execute.

    Got this. I've declared a new variable which is store buy_price and updates it in notify order method with order.executed.price.


Log in to reply
 

Looks like your connection to Backtrader Community was lost, please wait while we try to reconnect.