fixed porfolio value

This commit is contained in:
Boki 2025-07-03 18:49:48 -04:00
parent 8a9a4bc336
commit 70da2c68e5
4 changed files with 228 additions and 7 deletions

View file

@ -668,10 +668,17 @@ export class BacktestEngine extends EventEmitter {
private async updateEquityCurve(): Promise<void> {
const totalEquity = await this.getPortfolioValue();
this.equityCurve.push({
timestamp: this.currentTime,
value: totalEquity
});
// Don't add duplicate points at the same timestamp
const lastPoint = this.equityCurve[this.equityCurve.length - 1];
if (lastPoint && lastPoint.timestamp === this.currentTime) {
// Update the value instead of adding a duplicate
lastPoint.value = totalEquity;
} else {
this.equityCurve.push({
timestamp: this.currentTime,
value: totalEquity
});
}
}
private async getPortfolioValue(): Promise<number> {
@ -680,9 +687,23 @@ export class BacktestEngine extends EventEmitter {
return this.initialCapital;
}
// Get current P&L
const [realized, unrealized] = tradingEngine.getTotalPnl();
return this.initialCapital + realized + unrealized;
try {
// Get current P&L
const [realized, unrealized] = tradingEngine.getTotalPnl();
const totalValue = this.initialCapital + realized + unrealized;
// Ensure we never return 0 or negative values that would cause spikes
// This handles the case where getTotalPnl might not be initialized yet
if (totalValue <= 0 || isNaN(totalValue)) {
return this.initialCapital;
}
return totalValue;
} catch (error) {
// If getTotalPnl fails, return initial capital
this.container.logger.warn('Failed to get total P&L, using initial capital:', error);
return this.initialCapital;
}
}
private calculatePerformance(closedTrades: any[] = []): PerformanceMetrics {