How to code in Python to raise the stop level once when the p&l crosses above the quantity?

Benthomas
Benthomas edited February 2021 in Python client
Hi,

I created a program code to to exit the position when the pnl<-quantity.
ie. if I have a position in Nifty option with quantity 75(1 lot) and the pnl is less than -75 (one Rupee loss), I want to exit the position and it is working fine.

But what actually I need is, if the pnl once crosses 75 (>75), the stop loss level must be raised to 0(zero) and fixed for ever. I added some code lines, and when the pnl>75, stop is raised to 0, but when the price reverses (pnl<75), the stop again goes back to -75(instead of remaining at 0).

My logic and coding are not working..

Please help me to correct this code. I would be thankful to you.
I do not want to put BracketOrder or CoverOrder.

#=====Here is the issue===============================================

sl_factor=-1
if(pnl>quantity):
sl_factor=0

#=================================================================

#Exit the position when the pnl less than the predetermined level
if(pnl<quantity*sl_factor):
placeMarketOrder(tradingsymbol_pos,"sell", quantity)


#=================================================================

Tagged:
  • tahseen
    I think the problem is that you are initialising the sl_factor every time and thus it is getting reset

    Are you running this below code inside a quantity / PnL polling loop ? If yes then that is the cause. It should be outside

    sl_factor=-1


  • Benthomas
    Thank you Tahseen. I will try it tomorrow when the market is open.
    Best regards
Sign In or Register to comment.