Update closing position on BotStop

This commit is contained in:
2025-11-23 23:31:34 +07:00
parent 6429501b70
commit 47bea1b9b7
2 changed files with 78 additions and 41 deletions

View File

@@ -317,44 +317,8 @@ public class LiveTradingBotGrain : Grain, ILiveTradingBotGrain, IRemindable
private async Task StopAsyncInternal(bool isRestarting, string? reason = null)
{
// Only check for open positions if this is not part of a restart operation
if (!isRestarting)
{
await CloseAllOpenPositionsAsync();
// Verify positions are actually closed (even if CloseAllOpenPositionsAsync had timeouts/exceptions)
// This ensures we don't report failure if positions were successfully closed despite timeouts
try
{
var botId = this.GetPrimaryKey();
var positions = await ServiceScopeHelpers.WithScopedService<ITradingService, IEnumerable<Position>>(
_scopeFactory,
async tradingService => await tradingService.GetPositionsByInitiatorIdentifierAsync(botId));
var stillOpenPositions =
positions?.Where(p => p.IsOpen() || p.Status.Equals(PositionStatus.New)).ToList() ??
new List<Position>();
if (stillOpenPositions.Any())
{
_logger.LogWarning(
"Bot {GrainId} still has {Count} open positions after closure attempt: {Positions}",
botId, stillOpenPositions.Count,
string.Join(", ", stillOpenPositions.Select(p => p.Identifier)));
}
else
{
_logger.LogInformation("Bot {GrainId} - all positions verified as closed", botId);
}
}
catch (Exception ex)
{
// Don't fail the stop operation if we can't verify positions
_logger.LogWarning(ex,
"Could not verify position closure status for bot {GrainId}, continuing with stop",
this.GetPrimaryKey());
}
}
// Note: Position closing is now handled outside the grain in StopBotCommandHandler
// to avoid Orleans timeout. This method only handles fast grain operations.
// The check is now against the registry status
var botRegistry = GrainFactory.GetGrain<ILiveBotRegistryGrain>(0);
@@ -607,7 +571,7 @@ public class LiveTradingBotGrain : Grain, ILiveTradingBotGrain, IRemindable
if (_state.State.Config.IsForCopyTrading && _state.State.Config.MasterBotIdentifier.HasValue)
{
_logger.LogInformation("Checking copy trading authorization for bot {GrainId}", this.GetPrimaryKey());
// Check if copy trading validation should be bypassed (for testing)
var enableValidation = Environment.GetEnvironmentVariable("ENABLE_COPY_TRADING_VALIDATION")?
.Equals("true", StringComparison.OrdinalIgnoreCase) ?? true;