backtesting.py icon indicating copy to clipboard operation
backtesting.py copied to clipboard

Stop-loss order executed at a higher price than the market price

Open dlwocks31 opened this issue 4 years ago • 1 comments

Expected Behavior

Consider a stop-loss order placed at a stop-loss price p. When the opening price is way below the stop-loss price p, I would expect the stop-loss order to be executed at the opening price.

Actual Behavior

The stop-loss order is executed at the stop-loss price p, which is way higher than the opening price.

Steps to Reproduce

import pandas as pd
from backtesting import Strategy, Backtest

data = {
    'Open': [100, 100, 100, 50, 50],
    'High': [100, 100, 100, 50, 50],
    'Low': [100, 100, 100, 50, 50],
    'Close': [100, 100, 100, 50, 50],
}
dataframe = pd.DataFrame(data=data)

class BaseStrategy(Strategy):
    def init(self):
        pass
    def next(self):
        if self.data.Close[-1] == 100:
            self.buy(size=1, sl=90)
    
bt = Backtest(dataframe, BaseStrategy, cash=100, trade_on_close=True)
opt = bt.run()
bt.plot()
opt._trades['ExitPrice'][0] # Expected: 50, Actual: 90

image

Additional info

  • When the trade_on_close option is False, the code works as expected.
  • Backtesting version: 0.3.2

dlwocks31 avatar Oct 31 '21 05:10 dlwocks31