Update backtest message

This commit is contained in:
2025-07-17 15:01:30 +07:00
parent 27bed791c3
commit 3ba06f94be
3 changed files with 37 additions and 35 deletions

View File

@@ -93,12 +93,14 @@ namespace Managing.Application.Backtesting
try try
{ {
creditRequestId = await _kaigenService.DebitUserCreditsAsync(user, 3); creditRequestId = await _kaigenService.DebitUserCreditsAsync(user, 3);
_logger.LogInformation("Successfully debited credits for user {UserName} with request ID {RequestId}", _logger.LogInformation(
"Successfully debited credits for user {UserName} with request ID {RequestId}",
user.Name, creditRequestId); user.Name, creditRequestId);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Failed to debit credits for user {UserName}. Backtest will not proceed.", user.Name); _logger.LogError(ex, "Failed to debit credits for user {UserName}. Backtest will not proceed.",
user.Name);
throw new Exception($"Failed to debit credits: {ex.Message}"); throw new Exception($"Failed to debit credits: {ex.Message}");
} }
} }
@@ -130,11 +132,13 @@ namespace Managing.Application.Backtesting
var refundSuccess = await _kaigenService.RefundUserCreditsAsync(creditRequestId, user); var refundSuccess = await _kaigenService.RefundUserCreditsAsync(creditRequestId, user);
if (refundSuccess) if (refundSuccess)
{ {
_logger.LogInformation("Successfully refunded credits for user {UserName} after backtest failure", user.Name); _logger.LogInformation(
"Successfully refunded credits for user {UserName} after backtest failure", user.Name);
} }
else else
{ {
_logger.LogError("Failed to refund credits for user {UserName} after backtest failure", user.Name); _logger.LogError("Failed to refund credits for user {UserName} after backtest failure",
user.Name);
} }
} }
catch (Exception refundEx) catch (Exception refundEx)
@@ -192,7 +196,8 @@ namespace Managing.Application.Backtesting
tradingBot.User = user; tradingBot.User = user;
await tradingBot.LoadAccount(); await tradingBot.LoadAccount();
var result = await GetBacktestingResult(config, tradingBot, candles, user, withCandles, requestId, metadata); var result =
await GetBacktestingResult(config, tradingBot, candles, user, withCandles, requestId, metadata);
if (user != null) if (user != null)
{ {
@@ -332,7 +337,9 @@ namespace Managing.Application.Backtesting
Score = score, Score = score,
Id = Guid.NewGuid().ToString(), Id = Guid.NewGuid().ToString(),
RequestId = requestId, RequestId = requestId,
Metadata = metadata Metadata = metadata,
StartDate = candles.FirstOrDefault()!.OpenTime,
EndDate = candles.LastOrDefault()!.OpenTime,
}; };
// Send notification if backtest meets criteria // Send notification if backtest meets criteria
@@ -345,7 +352,6 @@ namespace Managing.Application.Backtesting
{ {
try try
{ {
if (backtest.Score > 80) if (backtest.Score > 80)
{ {
await _messengerService.SendBacktestNotification(backtest); await _messengerService.SendBacktestNotification(backtest);
@@ -448,9 +454,11 @@ namespace Managing.Application.Backtesting
return backtests; return backtests;
} }
public (IEnumerable<LightBacktest> Backtests, int TotalCount) GetBacktestsByRequestIdPaginated(string requestId, int page, int pageSize, string sortBy = "score", string sortOrder = "desc") public (IEnumerable<LightBacktest> Backtests, int TotalCount) GetBacktestsByRequestIdPaginated(string requestId,
int page, int pageSize, string sortBy = "score", string sortOrder = "desc")
{ {
var (backtests, totalCount) = _backtestRepository.GetBacktestsByRequestIdPaginated(requestId, page, pageSize, sortBy, sortOrder); var (backtests, totalCount) =
_backtestRepository.GetBacktestsByRequestIdPaginated(requestId, page, pageSize, sortBy, sortOrder);
return (backtests, totalCount); return (backtests, totalCount);
} }
@@ -531,9 +539,11 @@ namespace Managing.Application.Backtesting
} }
} }
public (IEnumerable<LightBacktest> Backtests, int TotalCount) GetBacktestsByUserPaginated(User user, int page, int pageSize, string sortBy = "score", string sortOrder = "desc") public (IEnumerable<LightBacktest> Backtests, int TotalCount) GetBacktestsByUserPaginated(User user, int page,
int pageSize, string sortBy = "score", string sortOrder = "desc")
{ {
var (backtests, totalCount) = _backtestRepository.GetBacktestsByUserPaginated(user, page, pageSize, sortBy, sortOrder); var (backtests, totalCount) =
_backtestRepository.GetBacktestsByUserPaginated(user, page, pageSize, sortBy, sortOrder);
return (backtests, totalCount); return (backtests, totalCount);
} }
} }

View File

@@ -161,14 +161,8 @@ public class MessengerService : IMessengerService
{ {
try try
{ {
var configMessage = BuildBacktestConfigMessage(backtest); var message = BuildBacktestMessage(backtest);
var resultsMessage = BuildBacktestResultsMessage(backtest); await _webhookService.SendMessage(message, "2775292276");
// Send configuration message first
await _webhookService.SendMessage(configMessage, "2775292276");
// Send results message second
await _webhookService.SendMessage(resultsMessage, "2775292276");
} }
catch (Exception e) catch (Exception e)
{ {
@@ -238,8 +232,8 @@ public class MessengerService : IMessengerService
var tradeCount = backtest.Positions?.Count ?? 0; var tradeCount = backtest.Positions?.Count ?? 0;
var finalPnl = backtest.FinalPnl; var finalPnl = backtest.FinalPnl;
var growthPercentage = backtest.GrowthPercentage; var growthPercentage = backtest.GrowthPercentage;
var maxDrawdown = backtest.Statistics?.MaxDrawdownPc ?? 0; var maxDrawdown = backtest.Statistics?.MaxDrawdown ?? 0;
var sharpeRatio = backtest.Statistics?.SharpeRatio ?? 0; var sharpeRatio = (backtest.Statistics?.SharpeRatio * 100) ?? 0;
// Get indicators list as comma-separated string // Get indicators list as comma-separated string
var indicators = config.Scenario?.Indicators != null && config.Scenario.Indicators.Any() var indicators = config.Scenario?.Indicators != null && config.Scenario.Indicators.Any()
@@ -247,30 +241,28 @@ public class MessengerService : IMessengerService
: "N/A"; : "N/A";
// MoneyManagement summary // MoneyManagement summary
var mmSl = config.MoneyManagement != null ? config.MoneyManagement.StopLoss.ToString("F2") : "N/A"; var mmSl = config.MoneyManagement != null ? (config.MoneyManagement.StopLoss * 100).ToString("F2") : "N/A";
var mmTp = config.MoneyManagement != null ? config.MoneyManagement.TakeProfit.ToString("F2") : "N/A"; var mmTp = config.MoneyManagement != null ? (config.MoneyManagement.TakeProfit * 100).ToString("F2") : "N/A";
var mmLev = config.MoneyManagement != null ? config.MoneyManagement.Leverage.ToString("F2") : "N/A"; var mmLev = config.MoneyManagement != null ? config.MoneyManagement.Leverage.ToString("F2") : "N/A";
var message = $"🚀 Excellent Backtest Results! 🚀\n\n" + var message = $"🚀 Excellent Backtest Results! 🚀\n\n" +
$"📊 Configuration:\n" + $"🔹 Symbol: {config.Ticker} | " +
$"🔹 Symbol: {config.Ticker}\n" +
$"⏱️ Timeframe: {config.Timeframe}\n" + $"⏱️ Timeframe: {config.Timeframe}\n" +
$"👤 Account: {config.AccountName}\n" + $"👤 Account: {config.AccountName}\n" +
$"💼 Money Management: 🛡️ SL: {mmSl}% | 🎯 TP: {mmTp}% | 📈 Lev: {mmLev}x\n" + $"💼 MM: 🛡️ SL: {mmSl}% | 🎯 TP: {mmTp}% | 📈 Lev: {mmLev}x\n" +
$"💰 Balance: {config.BotTradingBalance}\n" + $"💰 Balance: {config.BotTradingBalance:C}\n" +
$"🧩 Indicators: {indicators}\n" + $"🧩 Indicators: {indicators}\n" +
$"📅 Period: {backtest.StartDate:yyyy-MM-dd} to {backtest.EndDate:yyyy-MM-dd}\n" + $"📅 Period: {backtest.StartDate:yyyy-MM-dd} to {backtest.EndDate:yyyy-MM-dd}\n" +
$"⏳ Cooldown: {config.CooldownPeriod} | 🔥 Max Loss Streak: {config.MaxLossStreak}\n" + $"⏳ Cooldown: {config.CooldownPeriod} | 🔥 Max Loss Streak: {config.MaxLossStreak}\n" +
$"🔄 Flip Position: {(config.FlipPosition ? "Yes" : "No")} | 🔒 Flip Only When In Profit: {(config.FlipOnlyWhenInProfit ? "Yes" : "No")}\n" + $"🔄 Flipping: {(config.FlipPosition ? "Yes" : "No")} | 🔒 Flip Only When In Profit: {(config.FlipOnlyWhenInProfit ? "Yes" : "No")}\n" +
$"👀 Watching Only: {(config.IsForWatchingOnly ? "Yes" : "No")} | 🧪 Backtest Mode: {(config.IsForBacktest ? "Yes" : "No")}\n" + $"{(config.MaxPositionTimeHours.HasValue && config.MaxPositionTimeHours.Value > 0 ? $" Max Position Time (hrs): {config.MaxPositionTimeHours.Value} | " : "")}🏁 Close Early When Profitable: {(config.CloseEarlyWhenProfitable ? "Yes" : "No")}\n" +
$"⏰ Max Position Time (hrs): {(config.MaxPositionTimeHours?.ToString() ?? "N/A")} | 🏁 Close Early When Profitable: {(config.CloseEarlyWhenProfitable ? "Yes" : "No")}\n" + $"\n📈 Performance Metrics:\n" +
$"📈 Performance Metrics:\n" +
$"⭐ Score: {score:F1}/100\n" + $"⭐ Score: {score:F1}/100\n" +
$"🏆 Win Rate: {winRate:F1}%\n" + $"🏆 Win Rate: {winRate:F1}%\n" +
$"📊 Total Trades: {tradeCount}\n" + $"📊 Total Trades: {tradeCount}\n" +
$"💰 Final PnL: ${finalPnl:F2}\n" + $"💰 Final PnL: ${finalPnl:F2}\n" +
$"📈 Growth: {growthPercentage:F1}%\n" + $"📈 Growth: {growthPercentage:F1}%\n" +
$"📉 Max Drawdown: {maxDrawdown:F1}%\n" + $"📉 Max Drawdown: ${maxDrawdown:C}\n" +
$"📊 Sharpe Ratio: {sharpeRatio:F2}\n\n" + $"📊 Sharpe Ratio: {sharpeRatio:F2}\n\n" +
$"🆔 Backtest ID: {backtest.Id}"; $"🆔 Backtest ID: {backtest.Id}";

View File

@@ -54,7 +54,7 @@ type ApiStore = {
const getInitialEnvironment = (): Environment => { const getInitialEnvironment = (): Environment => {
const savedEnv = getCookie(ENV_COOKIE_NAME) as Environment const savedEnv = getCookie(ENV_COOKIE_NAME) as Environment
return savedEnv || 'production' return savedEnv || 'sandbox'
} }
const initialEnv = getInitialEnvironment() const initialEnv = getInitialEnvironment()