Price for stop loss/tp for order execution under next() function #570
-
Hello everyone, import backtesting
from backtesting import Backtest, Strategy
from backtesting.lib import crossover
from backtesting.test import SMA, GOOG
class SmaCross(Strategy):
n1 = 10
n2 = 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):
price = self.data.Close[-1]
if crossover(self.sma1, self.sma2):
self.buy()
elif crossover(self.sma2, self.sma1):
print(price)
self.sell()
bt = Backtest(GOOG, SmaCross,
cash=10000, commission=0,
exclusive_orders=True)
output = bt.run()
print(output) So, price (price = self.data.Close[-1]) returns the previous closing value before the new candlestick the buy of sell command executes on. This is the price that people seem to be using to build a stop loss (e.g.: self.buy(sl=price*0.92)) or take profit number when they execute a buy or sell. However, this close price can be a bit off from the Open price, or the entry price, for the buy or sell order. Doesn't it make more sense to build a stop loss or take profit price off of the entry price the order was actually executed on, or is this not the case/not possible in practice? Thanks for your help, Cory |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Imagine you're working with daily data, running your It's the same regardless of candle timeframe. You can, however, run the backtest with |
Beta Was this translation helpful? Give feedback.
Imagine you're working with daily data, running your
next()
procedure every day after market close. You're contemplating next day's orders. There's no tomorrow's Open price yet to help you.It's the same regardless of candle timeframe.
You can, however, run the backtest with
Backtest(..., trade_on_close=True)
, which is like running that procedure "a few milliseconds" before market close.