Skip to content

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

Closed
@dlwocks31

Description

@dlwocks31

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions