Skip to content

Commit 5e68bba

Browse files
committed
BUG: Fix stop-market and TP hit within the same bar
Fixes #1224 Thanks @mmarihart
1 parent 5e5dfdf commit 5e68bba

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

backtesting/backtesting.py

+6
Original file line numberDiff line numberDiff line change
@@ -1005,6 +1005,12 @@ def _process_orders(self):
10051005
if order.sl or order.tp:
10061006
if is_market_order:
10071007
reprocess_orders = True
1008+
# Order.stop and TP hit within the same bar, but SL wasn't. This case
1009+
# is not ambiguous, because stop and TP go in the same price direction.
1010+
elif stop_price and not order.limit and order.tp and (
1011+
(order.is_long and order.tp <= high and (order.sl or -np.inf) < low) or
1012+
(order.is_short and order.tp >= low and (order.sl or np.inf) > high)):
1013+
reprocess_orders = True
10081014
elif (low <= (order.sl or -np.inf) <= high or
10091015
low <= (order.tp or -np.inf) <= high):
10101016
warnings.warn(

backtesting/test/_test.py

+11
Original file line numberDiff line numberDiff line change
@@ -1106,3 +1106,14 @@ def next(self):
11061106

11071107
trades = Backtest(SHORT_DATA, S).run()._trades
11081108
self.assertEqual(trades['ExitPrice'].iloc[0], 104.95)
1109+
1110+
def test_stop_entry_and_tp_in_same_bar(self):
1111+
class S(_S):
1112+
def next(self):
1113+
i = len(self.data.index)
1114+
if i == 3:
1115+
self.sell(stop=108, tp=105, sl=113)
1116+
1117+
trades = Backtest(SHORT_DATA, S).run()._trades
1118+
self.assertEqual(trades['ExitBar'].iloc[0], 3)
1119+
self.assertEqual(trades['ExitPrice'].iloc[0], 105)

0 commit comments

Comments
 (0)