Fix a bit the spot trading

This commit is contained in:
2025-12-10 23:16:46 +07:00
parent 931af3d3af
commit 8ff9437400
8 changed files with 44 additions and 113 deletions

View File

@@ -114,7 +114,8 @@ public class SpotBot : TradingBotBase, ITradingBot
// Calculate PnL based on current token balance and current price
// For LONG spot position: PnL = (currentPrice - openPrice) * tokenBalance
var openPrice = position.Open.Price;
var pnlBeforeFees = TradingBox.CalculatePnL(openPrice, currentPrice, tokenBalance.Amount, 1, TradeDirection.Long);
var pnlBeforeFees =
TradingBox.CalculatePnL(openPrice, currentPrice, tokenBalance.Amount, 1, TradeDirection.Long);
// Update position PnL
UpdatePositionPnl(position.Identifier, pnlBeforeFees);
@@ -162,13 +163,9 @@ public class SpotBot : TradingBotBase, ITradingBot
// For spot trading, check token balances to verify position status
try
{
var balances = await ServiceScopeHelpers.WithScopedService<IExchangeService, List<Balance>>(
var tokenBalance = await ServiceScopeHelpers.WithScopedService<IExchangeService, Balance?>(
_scopeFactory,
async exchangeService => { return await exchangeService.GetBalances(Account); });
var tickerString = Config.Ticker.ToString();
var tokenBalance = balances.FirstOrDefault(b =>
b.TokenName?.Equals(tickerString, StringComparison.OrdinalIgnoreCase) == true);
async exchangeService => await exchangeService.GetBalance(Account, Config.Ticker));
var hasOpenPosition = Positions.Values.Any(p => p.IsOpen());
@@ -195,7 +192,7 @@ public class SpotBot : TradingBotBase, ITradingBot
return false; // Don't allow opening new position until resolved
}
}
else if (tokenBalance != null && tokenBalance.Amount > 0)
else if (tokenBalance != null && tokenBalance.Value > 1m)
{
// We have a token balance but no internal position - orphaned position
await LogWarningAsync(
@@ -235,26 +232,21 @@ public class SpotBot : TradingBotBase, ITradingBot
// For spot trading, fetch token balance directly and verify/match with internal position
try
{
var balances = await ServiceScopeHelpers.WithScopedService<IExchangeService, List<Balance>>(
var tokenBalance = await ServiceScopeHelpers.WithScopedService<IExchangeService, Balance?>(
_scopeFactory,
async exchangeService => { return await exchangeService.GetBalances(Account); });
// Find the token balance for the ticker
var tickerString = Config.Ticker.ToString();
var tokenBalance = balances.FirstOrDefault(b =>
b.TokenName?.Equals(tickerString, StringComparison.OrdinalIgnoreCase) == true);
async exchangeService => await exchangeService.GetBalance(Account, Config.Ticker));
if (tokenBalance != null && tokenBalance.Amount > 0)
{
// Verify that the token balance matches the position amount with 0.1% tolerance
var positionQuantity = internalPosition.Open.Quantity;
var tokenBalanceAmount = tokenBalance.Amount;
if (positionQuantity > 0)
{
var tolerance = positionQuantity * 0.001m; // 0.1% tolerance
var tolerance = positionQuantity * 0.003m; // 0.3% tolerance
var difference = Math.Abs(tokenBalanceAmount - positionQuantity);
if (difference > tolerance)
{
await LogWarningAsync(
@@ -301,13 +293,17 @@ public class SpotBot : TradingBotBase, ITradingBot
{
currentPrice = await ServiceScopeHelpers.WithScopedService<IExchangeService, decimal>(
_scopeFactory,
async exchangeService => { return await exchangeService.GetCurrentPrice(Account, Config.Ticker); });
async exchangeService =>
{
return await exchangeService.GetCurrentPrice(Account, Config.Ticker);
});
}
if (currentPrice > 0)
{
var openPrice = internalPosition.Open.Price;
var pnlBeforeFees = TradingBox.CalculatePnL(openPrice, currentPrice, actualTokenBalance, 1, TradeDirection.Long);
var pnlBeforeFees = TradingBox.CalculatePnL(openPrice, currentPrice, actualTokenBalance, 1,
TradeDirection.Long);
UpdatePositionPnl(positionForSignal.Identifier, pnlBeforeFees);
var totalFees = internalPosition.GasFees + internalPosition.UiFees;
@@ -584,13 +580,6 @@ public class SpotBot : TradingBotBase, ITradingBot
return (closingPrice, pnlCalculated);
}
protected override async Task<decimal> GetLastPriceForPositionOpeningAsync()
{
// For live trading, get current price from exchange
return await ServiceScopeHelpers.WithScopedService<IExchangeService, decimal>(_scopeFactory,
async exchangeService => { return await exchangeService.GetCurrentPrice(Account, Config.Ticker); });
}
protected override async Task UpdateSignalsCore(IReadOnlyList<Candle> candles,
Dictionary<IndicatorType, IndicatorsResultBase> preCalculatedIndicatorValues = null)
{
@@ -690,7 +679,8 @@ public class SpotBot : TradingBotBase, ITradingBot
// Spot-specific position opening: includes balance verification and live exchange calls
if (signal.Direction != TradeDirection.Long)
{
throw new InvalidOperationException($"Only LONG signals can open positions in spot trading. Received: {signal.Direction}");
throw new InvalidOperationException(
$"Only LONG signals can open positions in spot trading. Received: {signal.Direction}");
}
if (Account == null || Account.User == null)
@@ -776,5 +766,4 @@ public class SpotBot : TradingBotBase, ITradingBot
}
}
}
}
}