Skip to content

Commit bbf5830

Browse files
committed
Enforce limit orders to execute at limit price instead of open/close price, align with TradingView's behaviour
Change comparsions from lt/gt to lte/gte
1 parent f569f04 commit bbf5830

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

backtesting/backtesting.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -889,20 +889,24 @@ def _process_orders(self):
889889
# Determine purchase price.
890890
# Check if limit order can be filled.
891891
if order.limit:
892-
is_limit_hit = low < order.limit if order.is_long else high > order.limit
892+
is_limit_hit = low <= order.limit if order.is_long else high >= order.limit
893893
# When stop and limit are hit within the same bar, we pessimistically
894894
# assume limit was hit before the stop (i.e. "before it counts")
895895
is_limit_hit_before_stop = (is_limit_hit and
896-
(order.limit < (stop_price or -np.inf)
896+
(order.limit <= (stop_price or -np.inf)
897897
if order.is_long
898-
else order.limit > (stop_price or np.inf)))
898+
else order.limit >= (stop_price or np.inf)))
899899
if not is_limit_hit or is_limit_hit_before_stop:
900900
continue
901901

902902
# stop_price, if set, was hit within this bar
903-
price = (min(stop_price or open, order.limit)
904-
if order.is_long else
905-
max(stop_price or open, order.limit))
903+
# price = (min(stop_price or open, order.limit)
904+
# if order.is_long else
905+
# max(stop_price or open, order.limit))
906+
if is_limit_hit:
907+
price = order.limit
908+
else:
909+
price = stop_price or open
906910
else:
907911
# Market-if-touched / market order
908912
price = prev_close if self._trade_on_close else open

0 commit comments

Comments
 (0)