Fix ROI calculation for Strategy

This commit is contained in:
2025-10-08 19:37:24 +07:00
parent 76b087a6e4
commit 1a99224d18
5 changed files with 41 additions and 36 deletions

View File

@@ -400,24 +400,27 @@ public class TradingBotBase : ITradingBot
}
Position internalPosition = null;
List<Position> brokerPositions = null;
await ServiceScopeHelpers.WithScopedService<ITradingService>(_scopeFactory, async tradingService =>
{
internalPosition = Config.IsForBacktest
? positionForSignal
: await tradingService.GetPositionByIdentifierAsync(positionForSignal.Identifier);
var brokerPositions = await ServiceScopeHelpers.WithScopedService<ITradingService, List<Position>>(
_scopeFactory, async tradingService =>
{
internalPosition = Config.IsForBacktest
? positionForSignal
: await tradingService.GetPositionByIdentifierAsync(positionForSignal.Identifier);
if (Config.IsForBacktest)
{
brokerPositions = new List<Position> { internalPosition };
}
else
{
brokerPositions = await ServiceScopeHelpers.WithScopedService<IExchangeService, List<Position>>(
_scopeFactory,
async exchangeService => { return [.. await exchangeService.GetBrokerPositions(Account)]; });
}
});
if (Config.IsForBacktest)
{
return new List<Position> { internalPosition };
}
else
{
return await ServiceScopeHelpers.WithScopedService<IExchangeService, List<Position>>(
_scopeFactory,
async exchangeService =>
{
return [.. await exchangeService.GetBrokerPositions(Account)];
});
}
});
if (!Config.IsForBacktest)
{
@@ -625,11 +628,11 @@ public class TradingBotBase : ITradingBot
lastCandle = Config.IsForBacktest
? LastCandle
: await exchangeService.GetCandle(Account, Config.Ticker,
DateTime.UtcNow);
DateTime.UtcNow);
});
var currentTime = Config.IsForBacktest ? lastCandle.Date : DateTime.UtcNow;
var currentPnl = positionForSignal.ProfitAndLoss?.Realized ?? 0;
var currentPnl = positionForSignal.ProfitAndLoss?.Net ?? 0;
var pnlPercentage = positionForSignal.Open.Price * positionForSignal.Open.Quantity != 0
? Math.Round((currentPnl / (positionForSignal.Open.Price * positionForSignal.Open.Quantity)) * 100,
2)
@@ -1592,11 +1595,11 @@ public class TradingBotBase : ITradingBot
if (position.Open?.Status == TradeStatus.Filled)
{
Logger.LogInformation(
$"✅ Position Closed Successfully\nPosition: `{position.SignalIdentifier}`\nPnL: `${position.ProfitAndLoss?.Realized:F2}`");
$"✅ Position Closed Successfully\nPosition: `{position.SignalIdentifier}`\nPnL: `${position.ProfitAndLoss?.Net:F2}`");
if (position.ProfitAndLoss != null)
{
Config.BotTradingBalance += position.ProfitAndLoss.Realized;
Config.BotTradingBalance += position.ProfitAndLoss.Net;
Logger.LogInformation(
string.Format("💰 Balance Updated\nNew bot trading balance: `${0:F2}`",