Improve error handling and logging in SpotBot position closing
- Added try-catch block around position closing logic to handle potential failures gracefully. - Enhanced logging to provide detailed warnings when closing a position fails, ensuring the position status remains unchanged for retry on the next cycle. - Re-threw exceptions for unhandled cases to inform callers of operation failures, improving overall robustness of the SpotBot.
This commit is contained in:
@@ -970,8 +970,25 @@ public class SpotBot : TradingBotBase
|
|||||||
// SHORT signal closes the open LONG position
|
// SHORT signal closes the open LONG position
|
||||||
await LogInformationAsync(
|
await LogInformationAsync(
|
||||||
$"🔻 Short Signal - Closing Long Position\nClosing position `{openedPosition.Identifier}` due to SHORT signal\nSignal: `{signal.Identifier}`");
|
$"🔻 Short Signal - Closing Long Position\nClosing position `{openedPosition.Identifier}` due to SHORT signal\nSignal: `{signal.Identifier}`");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
await CloseTrade(previousSignal, openedPosition, openedPosition.Open, lastPrice, true);
|
await CloseTrade(previousSignal, openedPosition, openedPosition.Open, lastPrice, true);
|
||||||
|
// Only mark as Finished if close was successful
|
||||||
await SetPositionStatus(previousSignal.Identifier, PositionStatus.Finished);
|
await SetPositionStatus(previousSignal.Identifier, PositionStatus.Finished);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
await LogWarningAsync(
|
||||||
|
$"❌ Failed to Close Position on SHORT Signal\n" +
|
||||||
|
$"Position: `{openedPosition.Identifier}`\n" +
|
||||||
|
$"Signal: `{signal.Identifier}`\n" +
|
||||||
|
$"Error: {ex.Message}\n" +
|
||||||
|
$"Position status NOT changed - will retry on next cycle");
|
||||||
|
// Don't change position status if close failed
|
||||||
|
// The position will be retried on the next bot cycle
|
||||||
|
}
|
||||||
|
|
||||||
SetSignalStatus(signal.Identifier, SignalStatus.Expired);
|
SetSignalStatus(signal.Identifier, SignalStatus.Expired);
|
||||||
return null; // No new position opened for SHORT signals
|
return null; // No new position opened for SHORT signals
|
||||||
}
|
}
|
||||||
@@ -1084,6 +1101,11 @@ public class SpotBot : TradingBotBase
|
|||||||
await HandleClosedPosition(position, forceMarketClose ? lastPrice : null,
|
await HandleClosedPosition(position, forceMarketClose ? lastPrice : null,
|
||||||
forceMarketClose);
|
forceMarketClose);
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Re-throw exception for other cases so caller knows the operation failed
|
||||||
|
throw;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user