Enhance SpotBot position management and logging
- Introduced logic to check if the opening swap was canceled by the broker, marking positions as canceled when necessary. - Adjusted orphaned balance thresholds for ETH and other tokens to improve balance management. - Enhanced logging to provide detailed information on swap status, including warnings for canceled swaps and their implications on position management. - Added a new method to verify swap execution status, improving the robustness of position handling in SpotBot.
This commit is contained in:
@@ -183,8 +183,11 @@ public class SpotBot : TradingBotBase
|
||||
if (tokenBalance is { Amount: > 0 })
|
||||
{
|
||||
// Check if this is a meaningful balance or just gas reserves / dust
|
||||
// Minimum threshold: $10 USD value to be considered an orphaned position
|
||||
const decimal minOrphanedBalanceValue = 10m;
|
||||
// For ETH, use a higher threshold since gas reserves are expected to be significant
|
||||
// For other tokens, use a lower threshold
|
||||
decimal minOrphanedBalanceValue = Config.Ticker == Ticker.ETH
|
||||
? 100m // ETH: $100 threshold (gas reserves can be $20-50+, so this is safe)
|
||||
: 10m; // Other tokens: $10 threshold
|
||||
|
||||
if (tokenBalance.Value < minOrphanedBalanceValue)
|
||||
{
|
||||
@@ -194,6 +197,7 @@ public class SpotBot : TradingBotBase
|
||||
$"Token balance: `{tokenBalance.Amount:F8}`\n" +
|
||||
$"USD Value: `${tokenBalance.Value:F2}`\n" +
|
||||
$"Below orphaned threshold of `${minOrphanedBalanceValue:F2}`\n" +
|
||||
$"{(Config.Ticker == Ticker.ETH ? "(ETH gas reserve - expected behavior)" : "(Dust amount)")}\n" +
|
||||
$"Ignoring - safe to open new position");
|
||||
return true; // Safe to open new position - this is just dust/gas reserve
|
||||
}
|
||||
@@ -403,6 +407,39 @@ public class SpotBot : TradingBotBase
|
||||
// For spot trading, fetch token balance directly and verify/match with internal position
|
||||
try
|
||||
{
|
||||
// First, check if the opening swap was canceled by the broker
|
||||
// This prevents confusing warning messages about token balance mismatches
|
||||
if (internalPosition.Status == PositionStatus.New)
|
||||
{
|
||||
var swapWasCanceled = await CheckIfOpeningSwapWasCanceled(internalPosition);
|
||||
if (swapWasCanceled)
|
||||
{
|
||||
// Mark position as Canceled
|
||||
var previousStatus = internalPosition.Status;
|
||||
internalPosition.Status = PositionStatus.Canceled;
|
||||
internalPosition.Open.SetStatus(TradeStatus.Cancelled);
|
||||
positionForSignal.Open.SetStatus(TradeStatus.Cancelled);
|
||||
await SetPositionStatus(internalPosition.SignalIdentifier, PositionStatus.Canceled);
|
||||
|
||||
await UpdatePositionInDatabaseAsync(internalPosition);
|
||||
|
||||
await LogWarningAsync(
|
||||
$"❌ Position Opening Failed - Swap Canceled by Broker\n" +
|
||||
$"Position: `{internalPosition.Identifier}`\n" +
|
||||
$"Signal: `{internalPosition.SignalIdentifier}`\n" +
|
||||
$"Ticker: {Config.Ticker}\n" +
|
||||
$"Expected Quantity: `{internalPosition.Open.Quantity:F5}`\n" +
|
||||
$"Status Changed: `{previousStatus}` → `Canceled`\n" +
|
||||
$"The opening swap (USDC → {Config.Ticker}) was canceled by the ExchangeRouter contract\n" +
|
||||
$"Position will not be tracked or managed");
|
||||
|
||||
// Notify about the canceled position (using PositionClosed as PositionCanceled doesn't exist)
|
||||
await NotifyAgentAndPlatformAsync(NotificationEventType.PositionClosed, internalPosition);
|
||||
|
||||
return; // Exit - no further synchronization needed
|
||||
}
|
||||
}
|
||||
|
||||
var tokenBalance = await ServiceScopeHelpers.WithScopedService<IExchangeService, Balance?>(
|
||||
_scopeFactory,
|
||||
async exchangeService => await exchangeService.GetBalance(Account, Config.Ticker));
|
||||
@@ -632,13 +669,142 @@ public class SpotBot : TradingBotBase
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> CheckIfOpeningSwapWasCanceled(Position position)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Only check for canceled swaps if position is in New status
|
||||
// (positions that haven't been filled yet)
|
||||
if (position.Status != PositionStatus.New)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await LogDebugAsync(
|
||||
$"🔍 Checking for Canceled Opening Swap\n" +
|
||||
$"Position: `{position.Identifier}`\n" +
|
||||
$"Ticker: `{Config.Ticker}`");
|
||||
|
||||
// Get swap history from exchange to check for canceled orders
|
||||
// We need to check if the opening swap (USDC -> ETH for LONG) was canceled
|
||||
var positionHistory = await ServiceScopeHelpers.WithScopedService<IExchangeService, List<Position>>(
|
||||
_scopeFactory,
|
||||
async exchangeService =>
|
||||
{
|
||||
// Check swaps from 1 hour before position date to now
|
||||
// This covers the time window when the swap could have been canceled
|
||||
var fromDate = position.Date.AddHours(-1);
|
||||
var toDate = DateTime.UtcNow;
|
||||
return await exchangeService.GetSpotPositionHistory(Account, Config.Ticker, fromDate, toDate);
|
||||
});
|
||||
|
||||
if (positionHistory == null || positionHistory.Count == 0)
|
||||
{
|
||||
// No history found - swap might still be pending
|
||||
return false;
|
||||
}
|
||||
|
||||
// For a LONG position, the opening swap should be LONG (USDC -> Token)
|
||||
// If we find a LONG swap around the position creation time, check if it was actually executed
|
||||
var openingSwaps = positionHistory
|
||||
.Where(p => p.OriginDirection == TradeDirection.Long &&
|
||||
Math.Abs((p.Date - position.Date).TotalMinutes) < 10) // Within 10 minutes of position creation
|
||||
.OrderBy(p => Math.Abs((p.Date - position.Date).TotalSeconds))
|
||||
.ToList();
|
||||
|
||||
if (openingSwaps.Any())
|
||||
{
|
||||
// We found swap(s) around the position creation time
|
||||
// If the quantity matches our expected position quantity, this is our opening swap
|
||||
var matchingSwap = openingSwaps.FirstOrDefault(swap =>
|
||||
Math.Abs(swap.Open.Quantity - position.Open.Quantity) / position.Open.Quantity < 0.02m); // Within 2% tolerance
|
||||
|
||||
if (matchingSwap != null)
|
||||
{
|
||||
// Found the matching opening swap - it was executed successfully
|
||||
await LogDebugAsync(
|
||||
$"✅ Opening Swap Found and Executed\n" +
|
||||
$"Position: `{position.Identifier}`\n" +
|
||||
$"Swap Quantity: `{matchingSwap.Open.Quantity:F5}`\n" +
|
||||
$"Expected Quantity: `{position.Open.Quantity:F5}`\n" +
|
||||
$"Swap was successful");
|
||||
return false; // Swap was not canceled
|
||||
}
|
||||
}
|
||||
|
||||
// If we reach here, we didn't find a matching executed swap
|
||||
// This likely means the swap was canceled by the broker
|
||||
// Double-check by verifying the token balance is significantly lower than expected
|
||||
var tokenBalance = await ServiceScopeHelpers.WithScopedService<IExchangeService, Balance?>(
|
||||
_scopeFactory,
|
||||
async exchangeService => await exchangeService.GetBalance(Account, Config.Ticker));
|
||||
|
||||
if (tokenBalance != null && position.Open.Quantity > 0)
|
||||
{
|
||||
var tolerance = position.Open.Quantity * 0.10m; // 10% tolerance
|
||||
var difference = position.Open.Quantity - tokenBalance.Amount;
|
||||
|
||||
if (difference > tolerance)
|
||||
{
|
||||
// Token balance is significantly lower than expected position quantity
|
||||
// This confirms the swap was likely canceled
|
||||
await LogWarningAsync(
|
||||
$"❌ Opening Swap Appears to be Canceled by Broker\n" +
|
||||
$"Position: `{position.Identifier}`\n" +
|
||||
$"Expected Quantity: `{position.Open.Quantity:F5}`\n" +
|
||||
$"Actual Token Balance: `{tokenBalance.Amount:F5}`\n" +
|
||||
$"Difference: `{difference:F5}` (exceeds 10% tolerance)\n" +
|
||||
$"No matching executed swap found in history\n" +
|
||||
$"Position will be marked as Canceled");
|
||||
return true; // Swap was canceled
|
||||
}
|
||||
}
|
||||
|
||||
return false; // Swap status unclear - don't assume it was canceled
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "Error checking if opening swap was canceled for position {PositionId}", position.Identifier);
|
||||
await LogWarningAsync(
|
||||
$"⚠️ Error Checking for Canceled Swap\n" +
|
||||
$"Position: `{position.Identifier}`\n" +
|
||||
$"Error: {ex.Message}");
|
||||
return false; // On error, don't assume swap was canceled
|
||||
}
|
||||
}
|
||||
|
||||
protected override async Task HandleOrderManagementAndPositionStatus(LightSignal signal, Position internalPosition,
|
||||
Position positionForSignal)
|
||||
{
|
||||
// Spot trading doesn't use orders like futures - positions are opened via swaps
|
||||
// Just check if the swap was successful
|
||||
// Check if the opening swap was successful or canceled
|
||||
if (internalPosition.Status == PositionStatus.New)
|
||||
{
|
||||
// First, check if the opening swap was canceled by the broker
|
||||
var swapWasCanceled = await CheckIfOpeningSwapWasCanceled(internalPosition);
|
||||
if (swapWasCanceled)
|
||||
{
|
||||
// Mark position as Canceled
|
||||
internalPosition.Status = PositionStatus.Canceled;
|
||||
internalPosition.Open.SetStatus(TradeStatus.Cancelled);
|
||||
positionForSignal.Open.SetStatus(TradeStatus.Cancelled);
|
||||
await SetPositionStatus(signal.Identifier, PositionStatus.Canceled);
|
||||
|
||||
await UpdatePositionInDatabaseAsync(internalPosition);
|
||||
|
||||
await LogWarningAsync(
|
||||
$"❌ Position Opening Failed - Swap Canceled by Broker\n" +
|
||||
$"Position: `{internalPosition.Identifier}`\n" +
|
||||
$"Signal: `{signal.Identifier}`\n" +
|
||||
$"The opening swap was canceled by the ExchangeRouter contract\n" +
|
||||
$"Position status set to Canceled");
|
||||
|
||||
// Notify about the canceled position (using PositionClosed as PositionCanceled doesn't exist)
|
||||
await NotifyAgentAndPlatformAsync(NotificationEventType.PositionClosed, internalPosition);
|
||||
|
||||
return; // Exit - position is canceled
|
||||
}
|
||||
|
||||
// Check if swap was successful by verifying position status
|
||||
// For spot, if Open trade is Filled, the position is filled
|
||||
if (positionForSignal.Open?.Status == TradeStatus.Filled)
|
||||
|
||||
Reference in New Issue
Block a user