Skip to content

Stop orders do not work #1157

Closed
Closed
@felonfusk

Description

@felonfusk

Expected Behavior

  1. The stop order (not stop loss), should be triggered at T+1
  2. It should be triggered if high >= stop for buy, or low <= stop for sell.

Actual Behavior

  1. The stop orders seem to be triggered at T+2 basis
  2. The stop order does not trigger if price == stop
  3. The stop sell order caused the EntryBar > ExitBar and negative Duration

Steps to Reproduce

test1: a simple stop buy @ 16 which is placed at the end of bar0 and expected to be filled at bar1
test2: a buy with both stop @ 16 and limit @ 12, it should be filled at bar1 with the stop price (based on my understanding that it takes the more conservative/pessimistic number). But nothing got filled.
test3: a stop sell order which should be filled at bar1, but it showed that the wrong entry and exit bars

from backtesting import Backtest, Strategy
import pandas as pd

df = pd.DataFrame({'Open':[14,16,15,11],
                   'High':[19,17,16,11],
                   'Low':[13,10,14,11],
                   'Close':[18,12,15,11]})

class test1(Strategy):
    def init(self):
        pass
    def next(self):
        if len(self.orders) == 0:
            self.buy(stop=16)

class test2(Strategy):
    def init(self):
        pass
    def next(self):
        if len(self.orders) == 0:
            self.buy(stop=16, limit=12)

class test3(Strategy):
    def init(self):
        pass
    def next(self):
        if len(self.orders) == 0:
            self.sell(stop=12)

print(df)
for test in [test1, test2, test3]:
    bt = Backtest(df, test, cash=10000, trade_on_close=True, exclusive_orders=True)
    output = bt.run()
    print(output._trades)
   Open  High  Low  Close
0    14    19   13     18
1    16    17   10     12      <--- all 3 stop orders should be triggered here
2    15    16   14     15
3    11    11   11     11

Empty DataFrame
Columns: [Size, EntryBar, ExitBar, EntryPrice, ExitPrice, PnL, ReturnPct, EntryTime, ExitTime, Duration]
Index: []

Empty DataFrame
Columns: [Size, EntryBar, ExitBar, EntryPrice, ExitPrice, PnL, ReturnPct, EntryTime, ExitTime, Duration]
Index: []

   Size  EntryBar  ExitBar  ...  EntryTime  ExitTime  Duration
0  -833         3        2  ...          3         2        -1

Additional info

  • Backtesting version: 0.3.3

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