Remove orderBy to improve perfs

This commit is contained in:
2025-11-15 14:17:21 +07:00
parent bed25e7222
commit 49a693b44a
16 changed files with 62 additions and 62 deletions

View File

@@ -33,7 +33,7 @@ public class StDevContext : IndicatorBase
ProcessStDevSignals(stDev, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{
@@ -60,7 +60,6 @@ public class StDevContext : IndicatorBase
// Filter pre-calculated StdDev values to match the candles we're processing
stDev = preCalculatedValues.StdDev
.Where(s => candles.Any(c => c.Date == s.Date))
.OrderBy(s => s.Date)
.ToList();
}
@@ -72,7 +71,7 @@ public class StDevContext : IndicatorBase
ProcessStDevSignals(stDev, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{

View File

@@ -32,7 +32,7 @@ public class ChandelierExitIndicatorBase : IndicatorBase
{
ProcessChandelierSignals(candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{
@@ -61,11 +61,9 @@ public class ChandelierExitIndicatorBase : IndicatorBase
// Filter pre-calculated Chandelier values to match the candles we're processing
chandelierLong = preCalculatedValues.ChandelierLong
.Where(c => c.ChandelierExit.HasValue && candles.Any(candle => candle.Date == c.Date))
.OrderBy(c => c.Date)
.ToList();
chandelierShort = preCalculatedValues.ChandelierShort
.Where(c => c.ChandelierExit.HasValue && candles.Any(candle => candle.Date == c.Date))
.OrderBy(c => c.Date)
.ToList();
}
@@ -77,7 +75,7 @@ public class ChandelierExitIndicatorBase : IndicatorBase
ProcessChandelierSignalsWithPreCalculated(chandelierLong, chandelierShort, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{
@@ -127,7 +125,8 @@ public class ChandelierExitIndicatorBase : IndicatorBase
ProcessChandelierSignalsForType(chandelier, chandelierType, candles);
}
private void GetSignalsWithPreCalculated(ChandelierType chandelierType, List<ChandelierResult> chandelier, HashSet<Candle> candles)
private void GetSignalsWithPreCalculated(ChandelierType chandelierType, List<ChandelierResult> chandelier,
HashSet<Candle> candles)
{
ProcessChandelierSignalsForType(chandelier, chandelierType, candles);
}
@@ -139,7 +138,8 @@ public class ChandelierExitIndicatorBase : IndicatorBase
/// <param name="chandelier">Chandelier calculation results</param>
/// <param name="chandelierType">Type of Chandelier (Long or Short)</param>
/// <param name="candles">Candles to process</param>
private void ProcessChandelierSignalsForType(List<ChandelierResult> chandelier, ChandelierType chandelierType, HashSet<Candle> candles)
private void ProcessChandelierSignalsForType(List<ChandelierResult> chandelier, ChandelierType chandelierType,
HashSet<Candle> candles)
{
var chandelierCandle = MapChandelierToCandle(chandelier, candles.TakeLast(MinimumHistory));
if (chandelierCandle.Count == 0)

View File

@@ -47,7 +47,7 @@ public class DualEmaCrossIndicatorBase : EmaBaseIndicatorBase
ProcessDualEmaCrossSignals(fastEma, slowEma, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{
@@ -76,11 +76,9 @@ public class DualEmaCrossIndicatorBase : EmaBaseIndicatorBase
// Filter pre-calculated EMA values to match the candles we're processing
fastEma = preCalculatedValues.FastEma
.Where(e => candles.Any(c => c.Date == e.Date))
.OrderBy(e => e.Date)
.ToList();
slowEma = preCalculatedValues.SlowEma
.Where(e => candles.Any(c => c.Date == e.Date))
.OrderBy(e => e.Date)
.ToList();
}
@@ -92,7 +90,7 @@ public class DualEmaCrossIndicatorBase : EmaBaseIndicatorBase
ProcessDualEmaCrossSignals(fastEma, slowEma, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{

View File

@@ -41,7 +41,7 @@ public class EmaCrossIndicator : EmaBaseIndicatorBase
ProcessEmaCrossSignals(ema, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{
@@ -79,7 +79,7 @@ public class EmaCrossIndicator : EmaBaseIndicatorBase
ProcessEmaCrossSignals(ema, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{

View File

@@ -41,7 +41,7 @@ public class EmaCrossIndicatorBase : EmaBaseIndicatorBase
ProcessEmaCrossSignals(ema, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{
@@ -68,7 +68,6 @@ public class EmaCrossIndicatorBase : EmaBaseIndicatorBase
// Filter pre-calculated EMA values to match the candles we're processing
ema = preCalculatedValues.Ema
.Where(e => candles.Any(c => c.Date == e.Date))
.OrderBy(e => e.Date)
.ToList();
}
@@ -80,7 +79,7 @@ public class EmaCrossIndicatorBase : EmaBaseIndicatorBase
ProcessEmaCrossSignals(ema, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{

View File

@@ -43,7 +43,7 @@ public class LaggingSTC : IndicatorBase
ProcessLaggingStcSignals(stc, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{
@@ -70,7 +70,6 @@ public class LaggingSTC : IndicatorBase
// Filter pre-calculated STC values to match the candles we're processing
stc = preCalculatedValues.Stc
.Where(s => candles.Any(c => c.Date == s.Date))
.OrderBy(s => s.Date)
.ToList();
}
@@ -82,7 +81,7 @@ public class LaggingSTC : IndicatorBase
ProcessLaggingStcSignals(stc, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{

View File

@@ -36,7 +36,7 @@ public class MacdCrossIndicatorBase : IndicatorBase
ProcessMacdSignals(macd, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{
@@ -63,7 +63,6 @@ public class MacdCrossIndicatorBase : IndicatorBase
// Filter pre-calculated MACD values to match the candles we're processing
macd = preCalculatedValues.Macd
.Where(m => candles.Any(c => c.Date == m.Date))
.OrderBy(m => m.Date)
.ToList();
}
@@ -75,7 +74,7 @@ public class MacdCrossIndicatorBase : IndicatorBase
ProcessMacdSignals(macd, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{

View File

@@ -37,7 +37,7 @@ public class RsiDivergenceConfirmIndicatorBase : IndicatorBase
ProcessRsiDivergenceConfirmSignals(rsiResult, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{
@@ -65,7 +65,6 @@ public class RsiDivergenceConfirmIndicatorBase : IndicatorBase
var relevantCandles = candles.TakeLast(10 * Period.Value);
rsiResult = preCalculatedValues.Rsi
.Where(r => relevantCandles.Any(c => c.Date == r.Date))
.OrderBy(r => r.Date)
.ToList();
}
@@ -77,7 +76,7 @@ public class RsiDivergenceConfirmIndicatorBase : IndicatorBase
ProcessRsiDivergenceConfirmSignals(rsiResult, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{

View File

@@ -39,7 +39,7 @@ public class StcIndicatorBase : IndicatorBase
ProcessStcSignals(stc, candles);
}
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{
@@ -66,7 +66,6 @@ public class StcIndicatorBase : IndicatorBase
// Filter pre-calculated STC values to match the candles we're processing
stc = preCalculatedValues.Stc
.Where(s => candles.Any(c => c.Date == s.Date))
.OrderBy(s => s.Date)
.ToList();
}
@@ -78,7 +77,7 @@ public class StcIndicatorBase : IndicatorBase
ProcessStcSignals(stc, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{

View File

@@ -48,10 +48,10 @@ public class SuperTrendCrossEma : IndicatorBase
.Where(a => a.Adx.HasValue && a.Pdi.HasValue && a.Mdi.HasValue) // Ensure all values exist
.ToList();
ProcessSuperTrendCrossEmaSignals(superTrend, ema50, adxResults, candles, minimumRequiredHistory, adxThreshold);
ProcessSuperTrendCrossEmaSignals(superTrend, ema50, adxResults, candles, minimumRequiredHistory,
adxThreshold);
return Signals.Where(s => s.Confidence != Confidence.None)
.OrderBy(s => s.Date)
.ToList();
}
catch (RuleException)
@@ -111,7 +111,6 @@ public class SuperTrendCrossEma : IndicatorBase
// Filter pre-calculated SuperTrend values to match the candles we're processing
superTrend = preCalculatedValues.SuperTrend
.Where(s => s.SuperTrend.HasValue && candles.Any(c => c.Date == s.Date))
.OrderBy(s => s.Date)
.ToList();
}
@@ -132,10 +131,10 @@ public class SuperTrendCrossEma : IndicatorBase
.Where(a => a.Adx.HasValue && a.Pdi.HasValue && a.Mdi.HasValue)
.ToList();
ProcessSuperTrendCrossEmaSignals(superTrend, ema50, adxResults, candles, minimumRequiredHistory, adxThreshold);
ProcessSuperTrendCrossEmaSignals(superTrend, ema50, adxResults, candles, minimumRequiredHistory,
adxThreshold);
return Signals.Where(s => s.Confidence != Confidence.None)
.OrderBy(s => s.Date)
.ToList();
}
catch (RuleException)

View File

@@ -37,7 +37,7 @@ public class SuperTrendIndicatorBase : IndicatorBase
ProcessSuperTrendSignals(superTrend, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{
@@ -64,7 +64,6 @@ public class SuperTrendIndicatorBase : IndicatorBase
// Filter pre-calculated SuperTrend values to match the candles we're processing
superTrend = preCalculatedValues.SuperTrend
.Where(s => s.SuperTrend.HasValue && candles.Any(c => c.Date == s.Date))
.OrderBy(s => s.Date)
.ToList();
}
@@ -76,7 +75,7 @@ public class SuperTrendIndicatorBase : IndicatorBase
ProcessSuperTrendSignals(superTrend, candles);
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
return Signals.Where(s => s.Confidence != Confidence.None).ToList();
}
catch (RuleException)
{

View File

@@ -33,7 +33,7 @@ public class EmaTrendIndicatorBase : EmaBaseIndicatorBase
ProcessEmaTrendSignals(ema, candles);
return Signals.OrderBy(s => s.Date).ToList();
return Signals.ToList();
}
catch (RuleException)
{
@@ -60,7 +60,6 @@ public class EmaTrendIndicatorBase : EmaBaseIndicatorBase
// Filter pre-calculated EMA values to match the candles we're processing
ema = preCalculatedValues.Ema
.Where(e => candles.Any(c => c.Date == e.Date))
.OrderBy(e => e.Date)
.ToList();
}
@@ -72,7 +71,7 @@ public class EmaTrendIndicatorBase : EmaBaseIndicatorBase
ProcessEmaTrendSignals(ema, candles);
return Signals.OrderBy(s => s.Date).ToList();
return Signals.ToList();
}
catch (RuleException)
{

View File

@@ -44,7 +44,7 @@ public class StochRsiTrendIndicatorBase : IndicatorBase
ProcessStochRsiTrendSignals(stochRsi, candles);
return Signals.OrderBy(s => s.Date).ToList();
return Signals.ToList();
}
catch (RuleException)
{
@@ -71,7 +71,6 @@ public class StochRsiTrendIndicatorBase : IndicatorBase
// Filter pre-calculated StochRsi values to match the candles we're processing
stochRsi = preCalculatedValues.StochRsi
.Where(s => s.Signal.HasValue && candles.Any(c => c.Date == s.Date))
.OrderBy(s => s.Date)
.ToList();
}
@@ -83,7 +82,7 @@ public class StochRsiTrendIndicatorBase : IndicatorBase
ProcessStochRsiTrendSignals(stochRsi, candles);
return Signals.OrderBy(s => s.Date).ToList();
return Signals.ToList();
}
catch (RuleException)
{

View File

@@ -82,16 +82,16 @@ public static class TradingBox
// Validate required parameters
if (lightScenario == null)
throw new ArgumentNullException(nameof(lightScenario), "Scenario cannot be null");
if (newCandles == null)
throw new ArgumentNullException(nameof(newCandles), "Candles cannot be null");
// Empty candles or no indicators is a valid business case - return null
if (!newCandles.Any() || lightScenario.Indicators == null || !lightScenario.Indicators.Any())
{
return null;
}
var signalOnCandles = new List<LightSignal>();
foreach (var indicator in lightScenario.Indicators)
@@ -189,19 +189,19 @@ public static class TradingBox
{
// Only one strategy, return the single signal if it meets minimum confidence
var signal = signalOnCandles.Single();
// Check if signal meets minimum confidence threshold
// None confidence should always be rejected regardless of threshold
if (signal.Confidence == Confidence.None || signal.Confidence < config.MinimumConfidence)
{
return null; // Below minimum confidence threshold or None
}
return signal;
}
// Optimized: Sort only if needed, then convert to HashSet
var orderedSignals = signalOnCandles.OrderBy(s => s.Date).ToList();
var orderedSignals = signalOnCandles.ToList();
signalOnCandles = new HashSet<LightSignal>(orderedSignals);
// Check if all strategies produced signals - this is required for composite signals
@@ -246,7 +246,8 @@ public static class TradingBox
// Calculate confidence based on the average confidence of all signals
var averageConfidence = CalculateAverageConfidence(allDirectionalSignals);
if (finalDirection == TradeDirection.None || averageConfidence == Confidence.None || averageConfidence < config.MinimumConfidence)
if (finalDirection == TradeDirection.None || averageConfidence == Confidence.None ||
averageConfidence < config.MinimumConfidence)
{
return null; // No valid signal, None confidence, or below minimum confidence
}
@@ -465,12 +466,13 @@ public static class TradingBox
{
var stopLoss = 0M;
var takeProfit = 0M;
// Filter candles after the position's opening trade was filled, up to the next position
var candlesBeforeNextPosition = candles.Where(c =>
c.Date >= position.Open.Date && c.Date <= (nextPosition == null ? candles.Last().Date : nextPosition.Open.Date))
c.Date >= position.Open.Date &&
c.Date <= (nextPosition == null ? candles.Last().Date : nextPosition.Open.Date))
.ToList();
// If no candles after position opened, return zeros
if (!candlesBeforeNextPosition.Any())
{
@@ -585,8 +587,8 @@ public static class TradingBox
public static AgentSummaryMetrics CalculateAgentSummaryMetrics(List<Position> positions)
{
var validPositions = positions?
.Where(p => p.IsValidForMetrics())
.ToList() ?? new List<Position>();
.Where(p => p.IsValidForMetrics())
.ToList() ?? new List<Position>();
if (!validPositions.Any())
{
@@ -613,7 +615,8 @@ public static class TradingBox
/// <param name="positions">List of all positions to analyze</param>
/// <param name="previousTotalVolume">Previous total volume to ensure cumulative volume never decreases</param>
/// <returns>PlatformSummaryMetrics with all calculated values</returns>
public static PlatformSummaryMetrics CalculatePlatformSummaryMetrics(List<Position> positions, decimal previousTotalVolume = 0m)
public static PlatformSummaryMetrics CalculatePlatformSummaryMetrics(List<Position> positions,
decimal previousTotalVolume = 0m)
{
if (positions == null || !positions.Any())
{
@@ -660,12 +663,14 @@ public static class TradingBox
if (position.TakeProfit1?.Status == TradeStatus.Filled)
{
closingVolume += position.TakeProfit1.Price * position.TakeProfit1.Quantity * position.TakeProfit1.Leverage;
closingVolume += position.TakeProfit1.Price * position.TakeProfit1.Quantity *
position.TakeProfit1.Leverage;
}
if (position.TakeProfit2?.Status == TradeStatus.Filled)
{
closingVolume += position.TakeProfit2.Price * position.TakeProfit2.Quantity * position.TakeProfit2.Leverage;
closingVolume += position.TakeProfit2.Price * position.TakeProfit2.Quantity *
position.TakeProfit2.Leverage;
}
}
@@ -683,6 +688,7 @@ public static class TradingBox
{
volumeByAsset[ticker] = 0;
}
volumeByAsset[ticker] += positionVolume;
// Position count breakdown by asset - update state directly
@@ -690,6 +696,7 @@ public static class TradingBox
{
positionCountByAsset[ticker] = 0;
}
positionCountByAsset[ticker]++;
// Calculate fees and PnL for all positions
@@ -709,6 +716,7 @@ public static class TradingBox
{
positionCountByDirection[direction] = 0;
}
positionCountByDirection[direction]++;
}
}
@@ -1183,10 +1191,11 @@ public static class TradingBox
/// <param name="leverage">The leverage multiplier</param>
/// <param name="direction">The trade direction (Long or Short)</param>
/// <returns>The calculated PnL</returns>
public static decimal CalculatePnL(decimal entryPrice, decimal exitPrice, decimal quantity, decimal leverage, TradeDirection direction)
public static decimal CalculatePnL(decimal entryPrice, decimal exitPrice, decimal quantity, decimal leverage,
TradeDirection direction)
{
var positionSize = CalculatePositionSize(quantity, leverage);
if (direction == TradeDirection.Long)
{
return (exitPrice - entryPrice) * positionSize;
@@ -1301,7 +1310,8 @@ public static class TradingBox
/// <param name="maxLossStreak">Maximum allowed loss streak (0 or negative means no limit)</param>
/// <param name="signalDirection">The direction of the signal for the new position</param>
/// <returns>True if position can be opened, false if blocked by loss streak</returns>
public static bool CheckLossStreak(List<Position> recentPositions, int maxLossStreak, TradeDirection signalDirection)
public static bool CheckLossStreak(List<Position> recentPositions, int maxLossStreak,
TradeDirection signalDirection)
{
// If MaxLossStreak is 0, there's no limit
if (maxLossStreak <= 0)