-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Adjusting Stop Loss and Take Profit price #1015
-
I am messing around and want to make a strategy that uses the entry price to determine the take profit and stop loss price. So far I can not figure out how to change these values and I can not set them when the buy or sell order is made since the Price technically doesn't exist at that point.
troubleshooting
class DemaCross(Strategy):
fast = 10
slow = 30
def init(self):
self.DEMASlow = self.I(DEMA,self.data.Close.s,self.slow)
self.DEMAFast = self.I(DEMA,self.data.Close.s,self.fast)
def next(self):
if self.position.is_long:
self.trades.sl= self.trades.entry_price * .9
self.trades.tp = self.trades.entry_price * 1.1
if self.position.is_short:
self.trades.sl= self.trades.entry_price * 1.1
self.trades.tp = self.trades.entry_price * .9
if crossover(self.DEMASlow,self.DEMAFast):
self.buy(sl=None,tp=None)
elif crossover(self.DEMAFast,self.DEMASlow):
self.sell(sl=None,tp=None)
This is what I am trying to do instead. When the trade is executed, see if the trade is a long or short, then try and change the stop loss and take profit point. But this is not working, am I missing something simple?
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 2 comments 3 replies
-
"self.trades.sl= self.trades.entry_price * .9"
Type of "self.trades" is tuple.
"self.trades" include all trades information.
You had better extract each trade infomation by using for loop.
Example
for trade in self.trades:
if trade.is_long:
pass
elif trade.is_short:
pass
Beta Was this translation helpful? Give feedback.
All reactions
-
Just now, I am also having trouble using this "trades".
Beta Was this translation helpful? Give feedback.
All reactions
-
If you want to make a strategy that uses the entry price to determine the take profit and stop loss price,
following page is useful.
https://greyhoundanalytics.com/blog/stop-losses-in-backtestingpy/
If "trade_on_close=False" is used with Class Backtest's parameters, the entry price is open price of next day.
So, in this case, this logic is useless.
https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#backtesting.backtesting.Backtest
from backtesting import Backtest
from backtesting import Strategy
from backtesting.test import GOOG
class Strat(Strategy):
def init(self):
pass
# Step through bars one by one
def next(self):
price = self.data.Close[-1]
if self.position:
pass
else:
# Look at _Broker class for details on order processing
# What happens when we have sl and tp, etc.
self.buy(size=1, sl=price - 5, tp=price + 10)
# might want trade_on_close = True to deal with gapping for sl and tp
bt = Backtest(GOOG, Strat, cash=10_000)
bt.run()
bt.plot()
Beta Was this translation helpful? Give feedback.
All reactions
-
I understand that you are able to enter a trade at the close price in theory. But in reality, I wouldn’t be able to buy at the close price since the pattern I am trading doesn’t form until the end of a trading day. So I would have to use the open price of the next day. And with how the ‘next’ method is called the next day’s open price technically doesn’t exist. So I am not sure there is a work around. So I would like to use the default settings for buying but I would like the know the entry point or set the profit or loss based on the entry price.
Beta Was this translation helpful? Give feedback.
All reactions
-
If you use the open price of the next day, you can use the entry price after day you issued a purchase order (at next day or at next bar).
And you can set the set sl or tp.
Fllowing is sample.
from backtesting import Backtest, Strategy
from backtesting.lib import crossover
from backtesting.test import SMA, GOOG
import datetime as dt
import talib as ta
GOOG = GOOG[dt.datetime(2010,1,1):dt.datetime(2010,4,30)]
class SmaCross(Strategy):
n1 = 10
n2 = 20
x = 20
def init(self):
close = self.data.Close
self.sma1 = self.I(SMA, close, self.n1)
self.sma2 = self.I(SMA, close, self.n2)
def next(self):
self.x = self.x + 1
print("######################## Bar ", self.x , " ########################")
# strategy (buy or sell)
if crossover(self.sma1, self.sma2):
print("buy!!!")
self.buy()
print("number of self.trades: ", len(self.trades))
print("Note that the number of trades is 0 when you issued a purchase order.")
elif crossover(self.sma2, self.sma1):
print("sell!!!")
self.sell()
print("number of self.trades: ", len(self.trades))
print("Note that the number of trades is 0 when you issued a purchase order.")
# set a pl/tp
if len(self.trades) > 0 and self.trades[0].is_long:
self.trades[0].sl = self.trades[0].entry_price * 0.9
self.trades[0].tp = self.trades[0].entry_price * 1.1
elif len(self.trades) > 0 and self.trades[0].is_short:
self.trades[0].sl = self.trades[0].entry_price * 1.1
self.trades[0].tp = self.trades[0].entry_price * 0.9
# for checking
for trade in self.trades:
print("number of trade: ", len(self.trades))
print("trade: ", trade)
print("entry_bar", trade.entry_bar)
print("entry_price: ", trade.entry_price)
print("entry_time: ", trade.entry_time)
print("is_long: ", trade.is_long)
print("is_short: ", trade.is_short)
print("sl: ", trade.sl)
print("tp: ", trade.tp)
bt = Backtest(
GOOG,
SmaCross,
cash = 10000,
commission = 0,
exclusive_orders = True,
trade_on_close=False
)
output = bt.run()
print(output)
bt.plot()
Beta Was this translation helpful? Give feedback.