Fix SLTP for backtests

This commit is contained in:
2025-11-12 23:52:58 +07:00
parent 3b176c290c
commit 6d6f70ae00
5 changed files with 226 additions and 13 deletions

View File

@@ -1706,12 +1706,22 @@ public class TradingBotBase : ITradingBot
if (wasStopLossHit)
{
// Use actual execution price based on direction
closingPrice = position.OriginDirection == TradeDirection.Long
? minPriceRecent // For LONG, SL hits at the low
: maxPriceRecent; // For SHORT, SL hits at the high
// For backtesting: use the configured SL price to ensure consistent PnL per money management
// For live trading: use actual execution price to reflect real market conditions (slippage)
if (Config.IsForBacktest)
{
closingPrice = position.StopLoss.Price;
}
else
{
// Use actual execution price based on direction for live trading
closingPrice = position.OriginDirection == TradeDirection.Long
? minPriceRecent // For LONG, SL hits at the low
: maxPriceRecent; // For SHORT, SL hits at the high
position.StopLoss.Price = closingPrice;
}
position.StopLoss.SetPrice(closingPrice, 2);
position.StopLoss.SetDate(currentCandle.Date);
position.StopLoss.SetStatus(TradeStatus.Filled);
@@ -1729,17 +1739,28 @@ public class TradingBotBase : ITradingBot
await LogDebug(
$"🛑 Stop Loss Execution Confirmed\n" +
$"Position: `{position.Identifier}`\n" +
$"SL Price: `${closingPrice:F2}` was hit (was `${position.StopLoss.Price:F2}`)\n" +
$"Closing Price: `${closingPrice:F2}`\n" +
$"Configured SL: `${position.StopLoss.Price:F2}`\n" +
$"Recent Low: `${minPriceRecent:F2}` | Recent High: `${maxPriceRecent:F2}`");
}
else if (wasTakeProfitHit)
{
// Use actual execution price based on direction
closingPrice = position.OriginDirection == TradeDirection.Long
? maxPriceRecent // For LONG, TP hits at the high
: minPriceRecent; // For SHORT, TP hits at the low
// For backtesting: use the configured TP price to ensure consistent PnL per money management
// For live trading: use actual execution price to reflect real market conditions (slippage)
if (Config.IsForBacktest)
{
closingPrice = position.TakeProfit1.Price;
}
else
{
// Use actual execution price based on direction for live trading
closingPrice = position.OriginDirection == TradeDirection.Long
? maxPriceRecent // For LONG, TP hits at the high
: minPriceRecent; // FOR SHORT, TP hits at the low
position.TakeProfit1.Price = closingPrice;
}
position.TakeProfit1.SetPrice(closingPrice, 2);
position.TakeProfit1.SetDate(currentCandle.Date);
position.TakeProfit1.SetStatus(TradeStatus.Filled);
@@ -1752,7 +1773,8 @@ public class TradingBotBase : ITradingBot
await LogDebug(
$"🎯 Take Profit Execution Confirmed\n" +
$"Position: `{position.Identifier}`\n" +
$"TP Price: `${closingPrice:F2}` was hit (was `${position.TakeProfit1.Price:F2}`)\n" +
$"Closing Price: `${closingPrice:F2}`\n" +
$"Configured TP: `${position.TakeProfit1.Price:F2}`\n" +
$"Recent Low: `${minPriceRecent:F2}` | Recent High: `${maxPriceRecent:F2}`");
}
else