Re-update internal balance before opening position

This commit is contained in:
2025-10-27 10:25:45 +07:00
parent f816b8de50
commit abd5eb675c
2 changed files with 62 additions and 5 deletions

View File

@@ -169,6 +169,57 @@ public class TradingBotBase : ITradingBot
});
}
/// <summary>
/// Verifies the actual USDC balance and updates the config if the actual balance is less than the configured balance.
/// This prevents bots from trying to trade with more funds than are actually available.
/// </summary>
public async Task VerifyAndUpdateBalance()
{
if (Config.IsForBacktest) return;
if (Account == null)
{
Logger.LogWarning("Cannot verify balance: Account is null");
return;
}
try
{
// Fetch actual USDC balance
var actualBalance = await ServiceScopeHelpers.WithScopedService<IExchangeService, decimal>(_scopeFactory,
async exchangeService =>
{
var balances = await exchangeService.GetBalances(Account);
var usdcBalance = balances.FirstOrDefault(b => b.TokenName?.ToUpper() == "USDC");
return usdcBalance?.Amount ?? 0;
});
// Check if actual balance is less than configured balance
if (actualBalance < Config.BotTradingBalance)
{
Logger.LogWarning(
"Actual USDC balance ({ActualBalance:F2}) is less than configured balance ({ConfiguredBalance:F2}). Updating configuration.",
actualBalance, Config.BotTradingBalance);
// Create new config with updated balance
var newConfig = Config;
newConfig.BotTradingBalance = actualBalance;
// Use UpdateConfiguration to notify and log the change
await UpdateConfiguration(newConfig);
}
else
{
Logger.LogDebug(
"Balance verification passed. Actual: {ActualBalance:F2}, Configured: {ConfiguredBalance:F2}",
actualBalance, Config.BotTradingBalance);
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Error verifying and updating balance");
}
}
public async Task Run()
{
// Update signals for live trading only
@@ -970,6 +1021,12 @@ public class TradingBotBase : ITradingBot
try
{
// Verify actual balance before opening position
if (!Config.IsForBacktest)
{
await VerifyAndUpdateBalance();
}
var command = new OpenPositionRequest(
Config.AccountName,
Config.MoneyManagement,