Implementing a SL and TP exit in my strategies

I am currently working on gap up, gap down strategy. 


Create a column to store the value of long and short positions

data['positions'] = np.nan


Long entry condition

long_entry = data['Adj Open'] > data['Adj Close'].shift(1)


Short entry condition

short_entry = data['Adj Open'] < data['Adj Close'].shift(1)


Store 1 when long entry condition is true

data.loc[long_entry, 'positions'] = 1


Store -1 when short entry condition is true

data.loc[short_entry, 'positions'] = -1


Drop NaN values

data = data.dropna()



Here are the entries for the strategy but how would I exit using SL and TP. Let's assume SL = 0.03 and TP = 0.15. How would I implement tis in my exit and in my tradesheet? Thank you

Hi Jessy,



To do this you can set the exit condition of the strategy based on your stop loss and take profit level. Here's a step-by-step:

  1. Define the stop-loss and take profit percentage

    2. For a given date, if there is an open position, calculate the stop-loss and take-profit price levels. Check if the close of the day is less than the stop-loss price or greater than the take profit. If either of these conditions are met, you can exit on the given date.

    3. Finally, update the variables exit_date with the given date and exit_price with the close price of the given date. Assign '0' to the variable current_position.



    To get a detailed understanding of how these steps can be carried out in Python, you can also check the "Backtest With Stop-Loss and Take-Profit" notebook of the Backtesting Trading Strategies course.



    Thanks

    Rushda

Thank you, I had a look at the ATR trailing stop notebook and implemented that. Thank you for your help.