Fix config update + remove messages + Summary fix for not open position

This commit is contained in:
2025-10-08 02:52:11 +07:00
parent ff7e4ed3d3
commit 67065469a6
17 changed files with 209 additions and 159 deletions

View File

@@ -50,18 +50,18 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
// Daily reminder - runs at midnight (00:00 UTC)
var nextDailyTime = CandleHelpers.GetNextExpectedCandleTime(Timeframe.OneDay, now);
var timeUntilNextDay = nextDailyTime - now;
// Ensure dueTime is never negative - if it is, schedule for next day
if (timeUntilNextDay <= TimeSpan.Zero)
{
timeUntilNextDay = TimeSpan.FromDays(1).Add(TimeSpan.FromMinutes(3));
_logger.LogWarning("Due time was negative or zero, scheduling reminder for next day instead");
}
await this.RegisterOrUpdateReminder(_dailySnapshotReminder,
timeUntilNextDay, TimeSpan.FromDays(1).Add(TimeSpan.FromMinutes(3)));
_logger.LogInformation("Daily reminder scheduled - Next daily: {NextDaily}, Due time: {DueTime}",
_logger.LogInformation("Daily reminder scheduled - Next daily: {NextDaily}, Due time: {DueTime}",
nextDailyTime, timeUntilNextDay);
// Wipe daily snapshots except for the first day
@@ -136,12 +136,14 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
foreach (var position in positions)
{
if (!position.IsValidForMetrics()) continue;
// Calculate volume using the dedicated method
var positionVolume = TradingHelpers.GetVolumeForPosition(position);
totalVolume += positionVolume;
// Add to open interest for active positions only (only opening volume)
if (!position.IsFinished())
if (position.Status.Equals(PositionStatus.Filled))
{
var openingVolume = position.Open.Price * position.Open.Quantity * position.Open.Leverage;
totalOpenInterest += openingVolume;
@@ -175,7 +177,7 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
_state.State.PositionCountByAsset[ticker]++;
// Position count breakdown by direction - only count finished positions
if (!position.IsFinished())
if (position.IsValidForMetrics())
{
if (!_state.State.PositionCountByDirection.ContainsKey(direction))
{
@@ -201,6 +203,7 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
_state.State.PositionCountByDirection.GetValueOrDefault(TradeDirection.Short, 0));
_state.State.LastUpdated = DateTime.UtcNow;
await RefreshAgentCountAsync();
await _state.WriteStateAsync();
_logger.LogInformation("Platform summary data refreshed successfully");
@@ -344,7 +347,7 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
}
var originalCount = _state.State.DailySnapshots.Count;
// Keep only the first day snapshot
var firstSnapshot = _state.State.DailySnapshots.OrderBy(s => s.Date).First();
_state.State.DailySnapshots.Clear();
@@ -354,8 +357,8 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
_state.State.LastSnapshot = firstSnapshot.Date;
await _state.WriteStateAsync();
_logger.LogInformation("Wiped {WipedCount} daily snapshots, kept first snapshot from {FirstDate}",
_logger.LogInformation("Wiped {WipedCount} daily snapshots, kept first snapshot from {FirstDate}",
originalCount - 1, firstSnapshot.Date);
}
catch (Exception ex)
@@ -375,7 +378,7 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
// Get all positions to calculate missing snapshots
var positions = await _tradingService.GetAllDatabasePositionsAsync();
if (!positions.Any())
{
_logger.LogInformation("No positions found, skipping gap filling");
@@ -388,7 +391,7 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
var today = DateTime.UtcNow.Date;
// Determine the start date for gap filling
var startDate = _state.State.DailySnapshots.Any()
var startDate = _state.State.DailySnapshots.Any()
? _state.State.DailySnapshots.Max(s => s.Date).AddDays(1)
: earliestPositionDate;
@@ -419,8 +422,9 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
{
var snapshot = await CalculateDailySnapshotFromPositionsAsync(positions.ToList(), missingDate);
_state.State.DailySnapshots.Add(snapshot);
_logger.LogInformation("Created missing daily snapshot for {Date}: Volume={Volume}, PnL={PnL}, Positions={Positions}",
_logger.LogInformation(
"Created missing daily snapshot for {Date}: Volume={Volume}, PnL={PnL}, Positions={Positions}",
missingDate, snapshot.TotalVolume, snapshot.TotalPnL, snapshot.TotalLifetimePositionCount);
}
@@ -448,7 +452,8 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
/// <param name="positions">All positions to analyze</param>
/// <param name="targetDate">The date to calculate the snapshot up to</param>
/// <returns>A cumulative daily snapshot for the specified date</returns>
private async Task<DailySnapshot> CalculateDailySnapshotFromPositionsAsync(List<Position> positions, DateTime targetDate)
private async Task<DailySnapshot> CalculateDailySnapshotFromPositionsAsync(List<Position> positions,
DateTime targetDate)
{
var dayStart = targetDate;
var dayEnd = targetDate.AddDays(1);
@@ -468,7 +473,7 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
// Calculate open interest at different points during the day to find the maximum
var hourlyOpenInterest = new List<decimal>();
// Check open interest at each hour of the day (0-23)
for (int hour = 0; hour < 24; hour++)
{
@@ -478,11 +483,15 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
foreach (var position in positions)
{
// Check if position was active at this hour
var wasActiveAtThisHour = position.Date <= hourDateTime &&
(!position.IsFinished() ||
(position.StopLoss.Status == TradeStatus.Filled && position.StopLoss.Date > hourDateTime) ||
(position.TakeProfit1.Status == TradeStatus.Filled && position.TakeProfit1.Date > hourDateTime) ||
(position.TakeProfit2 != null && position.TakeProfit2.Status == TradeStatus.Filled && position.TakeProfit2.Date > hourDateTime));
var wasActiveAtThisHour = position.Date <= hourDateTime &&
(!position.IsFinished() ||
(position.StopLoss.Status == TradeStatus.Filled &&
position.StopLoss.Date > hourDateTime) ||
(position.TakeProfit1.Status == TradeStatus.Filled &&
position.TakeProfit1.Date > hourDateTime) ||
(position.TakeProfit2 != null &&
position.TakeProfit2.Status == TradeStatus.Filled &&
position.TakeProfit2.Date > hourDateTime));
if (wasActiveAtThisHour)
{
@@ -491,7 +500,7 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
hourlyOI += openingVolume;
}
}
hourlyOpenInterest.Add(hourlyOI);
}
@@ -502,16 +511,18 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
{
// Calculate CUMULATIVE volume up to this point in time
// Include all positions that were opened on or before the target date
_logger.LogDebug("Checking position {PositionId}: Position.Date={PositionDate}, TargetDate={TargetDate}, Position.Date.Date={PositionDateOnly}",
_logger.LogDebug(
"Checking position {PositionId}: Position.Date={PositionDate}, TargetDate={TargetDate}, Position.Date.Date={PositionDateOnly}",
position.Identifier, position.Date, targetDate, position.Date.Date);
// Add opening volume if position was opened on or before this day
// Use more flexible date comparison to handle timezone differences
if (position.Date.Date <= targetDate)
{
var openingVolume = position.Open.Price * position.Open.Quantity * position.Open.Leverage;
totalVolume += openingVolume;
_logger.LogDebug("Position {PositionId} opened on/before {TargetDate}: Opening volume = {OpeningVolume}",
_logger.LogDebug(
"Position {PositionId} opened on/before {TargetDate}: Opening volume = {OpeningVolume}",
position.Identifier, targetDate, openingVolume);
}
@@ -520,21 +531,29 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
{
if (position.StopLoss.Status == TradeStatus.Filled && position.StopLoss.Date.Date <= targetDate)
{
var closingVolume = position.StopLoss.Price * position.StopLoss.Quantity * position.StopLoss.Leverage;
var closingVolume = position.StopLoss.Price * position.StopLoss.Quantity *
position.StopLoss.Leverage;
totalVolume += closingVolume;
_logger.LogDebug("Position {PositionId} closed on/before {TargetDate} via StopLoss: Closing volume = {ClosingVolume}",
_logger.LogDebug(
"Position {PositionId} closed on/before {TargetDate} via StopLoss: Closing volume = {ClosingVolume}",
position.Identifier, targetDate, closingVolume);
}
if (position.TakeProfit1.Status == TradeStatus.Filled && position.TakeProfit1.Date.Date <= targetDate)
{
var closingVolume = position.TakeProfit1.Price * position.TakeProfit1.Quantity * position.TakeProfit1.Leverage;
var closingVolume = position.TakeProfit1.Price * position.TakeProfit1.Quantity *
position.TakeProfit1.Leverage;
totalVolume += closingVolume;
_logger.LogDebug("Position {PositionId} closed on/before {TargetDate} via TakeProfit1: Closing volume = {ClosingVolume}",
_logger.LogDebug(
"Position {PositionId} closed on/before {TargetDate} via TakeProfit1: Closing volume = {ClosingVolume}",
position.Identifier, targetDate, closingVolume);
}
if (position.TakeProfit2 != null && position.TakeProfit2.Status == TradeStatus.Filled && position.TakeProfit2.Date.Date <= targetDate)
if (position.TakeProfit2 != null && position.TakeProfit2.Status == TradeStatus.Filled &&
position.TakeProfit2.Date.Date <= targetDate)
{
var closingVolume = position.TakeProfit2.Price * position.TakeProfit2.Quantity * position.TakeProfit2.Leverage;
var closingVolume = position.TakeProfit2.Price * position.TakeProfit2.Quantity *
position.TakeProfit2.Leverage;
totalVolume += closingVolume;
}
}
@@ -543,7 +562,8 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
var wasClosedOnOrBeforeThisDay = position.IsFinished() && (
(position.StopLoss.Status == TradeStatus.Filled && position.StopLoss.Date.Date <= targetDate) ||
(position.TakeProfit1.Status == TradeStatus.Filled && position.TakeProfit1.Date.Date <= targetDate) ||
(position.TakeProfit2 != null && position.TakeProfit2.Status == TradeStatus.Filled && position.TakeProfit2.Date.Date <= targetDate)
(position.TakeProfit2 != null && position.TakeProfit2.Status == TradeStatus.Filled &&
position.TakeProfit2.Date.Date <= targetDate)
);
if (wasClosedOnOrBeforeThisDay)
@@ -563,7 +583,8 @@ public class PlatformSummaryGrain : Grain, IPlatformSummaryGrain, IRemindable
var totalAgents = await _agentService.GetTotalAgentCount();
var totalStrategies = _state.State.TotalActiveStrategies;
_logger.LogInformation("Calculated CUMULATIVE daily snapshot for {TargetDate}: CumVolume={TotalVolume}, MaxOpenInterest={MaxOpenInterest}, CumPositionCount={TotalPositionCount}",
_logger.LogInformation(
"Calculated CUMULATIVE daily snapshot for {TargetDate}: CumVolume={TotalVolume}, MaxOpenInterest={MaxOpenInterest}, CumPositionCount={TotalPositionCount}",
targetDate, totalVolume, maxOpenInterest, totalPositionCount);
return new DailySnapshot