Skip to content

trade_on_close not followed when SL/TP hit in the same candle. #945

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
admb4r opened this issue Mar 24, 2023 · 1 comment
Closed

trade_on_close not followed when SL/TP hit in the same candle. #945

admb4r opened this issue Mar 24, 2023 · 1 comment
Labels
duplicate This issue or pull request already exists

Comments

@admb4r
Copy link

admb4r commented Mar 24, 2023

Expected Behavior

When using the trade_on_close=False feature, trades will always occur on the following candle to which a trade was placed.

Actual Behavior

When a SL/TP is hit on the same candle a trade is placed, the logic does not cater for trade_on_close=False and instead places and closes the trade on the current candle.

I believe this is due to the check on line 908 of backtesting.py, which after a opening a trade with the correct time_index (the next candle in the backtest), instructs the backtest to reprocess orders if the trade is a market order and does not cater for the trade_on_close setting. This results in the SL/TP being checked for a trade that should not yet exist when trade_on_close=False.

# Open a new trade
if need_size:
self._open_trade(adjusted_price, need_size, order.sl, order.tp, time_index)
# We need to reprocess the SL/TP orders newly added to the queue.
# This allows e.g. SL hitting in the same bar the order was open.
# See https://github.com/kernc/backtesting.py/issues/119
if order.sl or order.tp:
if is_market_order:
reprocess_orders = True
elif (low <= (order.sl or -np.inf) <= high or
low <= (order.tp or -np.inf) <= high):
warnings.warn(
f"({data.index[-1]}) A contingent SL/TP order would execute in the "
"same bar its parent stop/limit order was turned into a trade. "
"Since we can't assert the precise intra-candle "
"price movement, the affected SL/TP order will instead be executed on "
"the next (matching) price/bar, making the result (of this trade) "
"somewhat dubious. "
"See https://github.com/kernc/backtesting.py/issues/119",
UserWarning)

@kernc
Copy link
Owner

kernc commented Feb 3, 2025

Hopefully fixed in 4aee89a.

@kernc kernc closed this as completed Feb 3, 2025
@kernc kernc added the duplicate This issue or pull request already exists label Feb 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
duplicate This issue or pull request already exists
Projects
None yet
Development

No branches or pull requests

2 participants