cleaned up web-app
This commit is contained in:
parent
805ce0ebf1
commit
3843dc95a3
21 changed files with 105 additions and 2420 deletions
|
|
@ -46,15 +46,32 @@ export const BacktestChart = memo(function BacktestChart({ result, isLoading }:
|
|||
|
||||
// Find trades for this symbol
|
||||
const symbolTrades = result.trades?.filter(t => t.symbol === symbol) || [];
|
||||
console.log('Symbol trades for', symbol, ':', symbolTrades);
|
||||
|
||||
const tradeMarkers = symbolTrades
|
||||
.filter(trade => trade.entryPrice != null && trade.entryDate != null)
|
||||
.map(trade => ({
|
||||
time: new Date(trade.entryDate).getTime() / 1000,
|
||||
position: 'belowBar' as const,
|
||||
color: trade.side === 'buy' ? '#10b981' : '#ef4444',
|
||||
shape: trade.side === 'buy' ? 'arrowUp' : 'arrowDown' as const,
|
||||
text: `${trade.side === 'buy' ? 'Buy' : 'Sell'} @ $${trade.entryPrice.toFixed(2)}`
|
||||
}));
|
||||
.filter(trade => {
|
||||
// Check multiple possible field names
|
||||
const hasPrice = trade.price != null || trade.entryPrice != null;
|
||||
const hasTime = trade.timestamp != null || trade.entryDate != null || trade.date != null;
|
||||
return hasPrice && hasTime;
|
||||
})
|
||||
.map(trade => {
|
||||
// Use whatever field names are present
|
||||
const price = trade.price || trade.entryPrice;
|
||||
const timestamp = trade.timestamp || trade.entryDate || trade.date;
|
||||
const side = trade.side || (trade.quantity > 0 ? 'buy' : 'sell');
|
||||
|
||||
return {
|
||||
time: new Date(timestamp).getTime() / 1000,
|
||||
position: 'belowBar' as const,
|
||||
color: side === 'buy' ? '#10b981' : '#ef4444',
|
||||
shape: (side === 'buy' ? 'arrowUp' : 'arrowDown') as const,
|
||||
text: `${side === 'buy' ? 'Buy' : 'Sell'} @ $${price.toFixed(2)}`,
|
||||
price: price
|
||||
};
|
||||
});
|
||||
|
||||
console.log('Trade markers:', tradeMarkers);
|
||||
|
||||
const processedOhlcData = ohlcData
|
||||
.filter(d => d && d.timestamp != null && d.open != null && d.high != null && d.low != null && d.close != null)
|
||||
|
|
|
|||
|
|
@ -1,147 +0,0 @@
|
|||
import {
|
||||
ArrowPathIcon,
|
||||
ForwardIcon,
|
||||
PauseIcon,
|
||||
PlayIcon,
|
||||
StopIcon,
|
||||
} from '@heroicons/react/24/solid';
|
||||
import type { BacktestStatus } from '../types';
|
||||
|
||||
interface BacktestControlsProps {
|
||||
status: BacktestStatus;
|
||||
onStart: () => void;
|
||||
onPause: () => void;
|
||||
onResume: () => void;
|
||||
onStop: () => void;
|
||||
onStep: () => void;
|
||||
currentTime: number | null;
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
}
|
||||
|
||||
export function BacktestControls({
|
||||
status,
|
||||
onStart,
|
||||
onPause,
|
||||
onResume,
|
||||
onStop,
|
||||
onStep,
|
||||
currentTime,
|
||||
startTime,
|
||||
endTime,
|
||||
}: BacktestControlsProps) {
|
||||
const progress = currentTime
|
||||
? ((currentTime - startTime) / (endTime - startTime)) * 100
|
||||
: 0;
|
||||
|
||||
const formatTime = (timestamp: number) => {
|
||||
return new Date(timestamp).toLocaleString();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-surface-secondary p-4 rounded-lg border border-border">
|
||||
<h2 className="text-base font-medium text-text-primary mb-4">Controls</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex gap-2">
|
||||
{status === 'configured' || status === 'stopped' ? (
|
||||
<button
|
||||
onClick={onStart}
|
||||
className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-success text-white rounded-md text-sm font-medium hover:bg-success/90 transition-colors"
|
||||
>
|
||||
<PlayIcon className="w-4 h-4" />
|
||||
Start
|
||||
</button>
|
||||
) : status === 'running' ? (
|
||||
<button
|
||||
onClick={onPause}
|
||||
className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-warning text-white rounded-md text-sm font-medium hover:bg-warning/90 transition-colors"
|
||||
>
|
||||
<PauseIcon className="w-4 h-4" />
|
||||
Pause
|
||||
</button>
|
||||
) : status === 'paused' ? (
|
||||
<button
|
||||
onClick={onResume}
|
||||
className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-success text-white rounded-md text-sm font-medium hover:bg-success/90 transition-colors"
|
||||
>
|
||||
<PlayIcon className="w-4 h-4" />
|
||||
Resume
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
{(status === 'running' || status === 'paused') && (
|
||||
<button
|
||||
onClick={onStop}
|
||||
className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-error text-white rounded-md text-sm font-medium hover:bg-error/90 transition-colors"
|
||||
>
|
||||
<StopIcon className="w-4 h-4" />
|
||||
Stop
|
||||
</button>
|
||||
)}
|
||||
|
||||
{status === 'paused' && (
|
||||
<button
|
||||
onClick={onStep}
|
||||
className="inline-flex items-center justify-center gap-2 px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
|
||||
>
|
||||
<ForwardIcon className="w-4 h-4" />
|
||||
Step
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{status !== 'idle' && status !== 'configured' && (
|
||||
<>
|
||||
<div>
|
||||
<div className="flex justify-between text-sm text-text-secondary mb-1">
|
||||
<span>Progress</span>
|
||||
<span>{progress.toFixed(1)}%</span>
|
||||
</div>
|
||||
<div className="w-full bg-background rounded-full h-2 overflow-hidden">
|
||||
<div
|
||||
className="bg-primary-500 h-2 transition-all duration-300"
|
||||
style={{ width: `${progress}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-text-secondary">Status</span>
|
||||
<span className={`text-text-primary font-medium ${
|
||||
status === 'running' ? 'text-success' :
|
||||
status === 'paused' ? 'text-warning' :
|
||||
status === 'completed' ? 'text-primary-400' :
|
||||
status === 'error' ? 'text-error' :
|
||||
'text-text-muted'
|
||||
}`}>
|
||||
{status.charAt(0).toUpperCase() + status.slice(1)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{currentTime && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-text-secondary">Current Time</span>
|
||||
<span className="text-text-primary text-xs">
|
||||
{formatTime(currentTime)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === 'completed' && (
|
||||
<button
|
||||
onClick={onStart}
|
||||
className="w-full inline-flex items-center justify-center gap-2 px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
|
||||
>
|
||||
<ArrowPathIcon className="w-4 h-4" />
|
||||
Run Again
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,227 +0,0 @@
|
|||
import type { BacktestStatus } from '../types';
|
||||
import type { BacktestResult } from '../services/backtestApi';
|
||||
import { MetricsCard } from './MetricsCard';
|
||||
import { PositionsTable } from './PositionsTable';
|
||||
import { TradeLog } from './TradeLog';
|
||||
import { Chart } from '../../../components/charts';
|
||||
import { useState, useMemo } from 'react';
|
||||
|
||||
interface BacktestResultsProps {
|
||||
status: BacktestStatus;
|
||||
results: BacktestResult | null;
|
||||
currentTime: number | null;
|
||||
}
|
||||
|
||||
export function BacktestResults({ status, results, currentTime }: BacktestResultsProps) {
|
||||
const [selectedSymbol, setSelectedSymbol] = useState<string>('');
|
||||
|
||||
if (status === 'idle') {
|
||||
return (
|
||||
<div className="bg-surface-secondary p-8 rounded-lg border border-border h-full flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-2">
|
||||
Configure Your Backtest
|
||||
</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Set up your strategy parameters and click "Configure Backtest" to begin.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (status === 'configured') {
|
||||
return (
|
||||
<div className="bg-surface-secondary p-8 rounded-lg border border-border h-full flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-2">
|
||||
Ready to Start
|
||||
</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Click the "Start" button to begin backtesting your strategy.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (status === 'running' && !results) {
|
||||
return (
|
||||
<div className="bg-surface-secondary p-8 rounded-lg border border-border h-full flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-t-2 border-primary-500 mx-auto mb-4"></div>
|
||||
<h3 className="text-lg font-medium text-text-primary mb-2">
|
||||
Running Backtest...
|
||||
</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Processing historical data and executing trades.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!results) {
|
||||
return (
|
||||
<div className="bg-surface-secondary p-8 rounded-lg border border-border h-full flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-2">
|
||||
No Results Yet
|
||||
</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Results will appear here once the backtest is complete.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 h-full overflow-y-auto">
|
||||
{/* Metrics Overview */}
|
||||
<div className="grid grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
<MetricsCard
|
||||
title="Total Return"
|
||||
value={`${(results.metrics.totalReturn || 0) >= 0 ? '+' : ''}${(results.metrics.totalReturn || 0).toFixed(2)}%`}
|
||||
trend={(results.metrics.totalReturn || 0) >= 0 ? 'up' : 'down'}
|
||||
/>
|
||||
<MetricsCard
|
||||
title="Sharpe Ratio"
|
||||
value={results.metrics.sharpeRatio?.toFixed(2) || '0.00'}
|
||||
trend={(results.metrics.sharpeRatio || 0) >= 1 ? 'up' : 'down'}
|
||||
/>
|
||||
<MetricsCard
|
||||
title="Max Drawdown"
|
||||
value={`${((results.metrics.maxDrawdown || 0) * 100).toFixed(2)}%`}
|
||||
trend="down"
|
||||
/>
|
||||
<MetricsCard
|
||||
title="Win Rate"
|
||||
value={`${(results.metrics.winRate || 0).toFixed(1)}%`}
|
||||
trend={(results.metrics.winRate || 0) >= 50 ? 'up' : 'down'}
|
||||
/>
|
||||
<MetricsCard
|
||||
title="Total Trades"
|
||||
value={(results.metrics.totalTrades || 0).toString()}
|
||||
/>
|
||||
{results.metrics.profitFactor !== null && results.metrics.profitFactor !== undefined && (
|
||||
<MetricsCard
|
||||
title="Profit Factor"
|
||||
value={results.metrics.profitFactor.toFixed(2)}
|
||||
trend={results.metrics.profitFactor >= 1 ? 'up' : 'down'}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Performance Chart */}
|
||||
<div className="bg-surface-secondary p-4 rounded-lg border border-border">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="text-base font-medium text-text-primary">
|
||||
Portfolio Performance
|
||||
</h3>
|
||||
{results.ohlcData && Object.keys(results.ohlcData).length > 1 && (
|
||||
<select
|
||||
value={selectedSymbol || Object.keys(results.ohlcData)[0]}
|
||||
onChange={(e) => setSelectedSymbol(e.target.value)}
|
||||
className="px-3 py-1 text-sm bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
|
||||
>
|
||||
{Object.keys(results.ohlcData).map(symbol => (
|
||||
<option key={symbol} value={symbol}>{symbol}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
{(() => {
|
||||
const hasOhlcData = results.ohlcData && Object.keys(results.ohlcData).length > 0;
|
||||
const hasEquityData = results.equity && results.equity.length > 0;
|
||||
|
||||
if (hasOhlcData) {
|
||||
const activeSymbol = selectedSymbol || Object.keys(results.ohlcData)[0];
|
||||
const ohlcData = results.ohlcData[activeSymbol];
|
||||
|
||||
// Create trade markers for the selected symbol (individual fills)
|
||||
const tradeMarkers = results.trades
|
||||
.filter(trade => trade.symbol === activeSymbol)
|
||||
.map(trade => {
|
||||
// Buy = green up arrow, Sell = red down arrow
|
||||
const isBuy = trade.side === 'buy';
|
||||
const pnlText = trade.pnl !== undefined ? ` (${trade.pnl >= 0 ? '+' : ''}${trade.pnl.toFixed(2)})` : '';
|
||||
const positionText = ` → ${trade.positionAfter > 0 ? '+' : ''}${trade.positionAfter}`;
|
||||
|
||||
return {
|
||||
time: Math.floor(new Date(trade.timestamp).getTime() / 1000),
|
||||
position: isBuy ? 'belowBar' as const : 'aboveBar' as const,
|
||||
color: isBuy ? '#10b981' : '#ef4444',
|
||||
shape: isBuy ? 'arrowUp' as const : 'arrowDown' as const,
|
||||
text: `${trade.side.toUpperCase()} ${trade.quantity}@${trade.price.toFixed(2)}${positionText}${pnlText}`,
|
||||
id: trade.id,
|
||||
price: trade.price
|
||||
};
|
||||
});
|
||||
|
||||
// Convert OHLC data timestamps
|
||||
const chartData = ohlcData.map((bar: any) => ({
|
||||
...bar,
|
||||
time: bar.timestamp || bar.time
|
||||
}));
|
||||
|
||||
return (
|
||||
<Chart
|
||||
data={chartData}
|
||||
height={400}
|
||||
type="candlestick"
|
||||
showVolume={true}
|
||||
theme="dark"
|
||||
overlayData={hasEquityData ? [
|
||||
{
|
||||
name: 'Portfolio Value',
|
||||
data: results.equity.map(point => ({
|
||||
time: Math.floor(new Date(point.date).getTime() / 1000),
|
||||
value: point.value
|
||||
})),
|
||||
color: '#10b981',
|
||||
lineWidth: 3
|
||||
}
|
||||
] : []}
|
||||
tradeMarkers={tradeMarkers}
|
||||
className="rounded"
|
||||
/>
|
||||
);
|
||||
} else if (hasEquityData) {
|
||||
return (
|
||||
<Chart
|
||||
data={results.equity.map(point => ({
|
||||
time: Math.floor(new Date(point.date).getTime() / 1000),
|
||||
value: point.value
|
||||
}))}
|
||||
height={400}
|
||||
type="area"
|
||||
showVolume={false}
|
||||
theme="dark"
|
||||
className="rounded"
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<div className="h-96 bg-background rounded border border-border flex items-center justify-center">
|
||||
<p className="text-sm text-text-muted">
|
||||
No data available
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
})()}
|
||||
</div>
|
||||
|
||||
{/* Trade Log */}
|
||||
{results.trades && results.trades.length > 0 && (
|
||||
<div className="bg-surface-secondary p-4 rounded-lg border border-border">
|
||||
<h3 className="text-base font-medium text-text-primary mb-4">
|
||||
Trade Log ({results.trades.length} fills)
|
||||
</h3>
|
||||
<TradeLog trades={results.trades} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@ import { DataTable } from '@/components/ui/DataTable';
|
|||
import type { ColumnDef } from '@tanstack/react-table';
|
||||
|
||||
interface BacktestTradesProps {
|
||||
result: BacktestResult | null;
|
||||
result: any | null;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
|
|
@ -28,7 +28,10 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
|
|||
);
|
||||
}
|
||||
|
||||
const columns: ColumnDef<typeof result.trades[0]>[] = [
|
||||
// Add debug logging
|
||||
console.log('Trades data:', result.trades);
|
||||
|
||||
const columns: ColumnDef<any>[] = [
|
||||
{
|
||||
accessorKey: 'symbol',
|
||||
header: 'Symbol',
|
||||
|
|
@ -38,11 +41,12 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
|
|||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'side',
|
||||
id: 'side',
|
||||
header: 'Side',
|
||||
size: 80,
|
||||
cell: ({ getValue }) => {
|
||||
const side = getValue() as string || 'unknown';
|
||||
cell: ({ row }) => {
|
||||
const trade = row.original;
|
||||
const side = trade.side || (trade.quantity > 0 ? 'buy' : 'sell');
|
||||
return (
|
||||
<span className={`inline-flex px-2 py-1 text-xs font-medium rounded-md ${
|
||||
side === 'buy'
|
||||
|
|
@ -55,11 +59,12 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
|
|||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'entryDate',
|
||||
header: 'Entry Date',
|
||||
id: 'date',
|
||||
header: 'Date',
|
||||
size: 180,
|
||||
cell: ({ getValue }) => {
|
||||
const date = getValue() as string;
|
||||
cell: ({ row }) => {
|
||||
const trade = row.original;
|
||||
const date = trade.timestamp || trade.entryDate || trade.date;
|
||||
return (
|
||||
<span className="text-sm text-text-secondary">
|
||||
{date ? new Date(date).toLocaleString() : '-'}
|
||||
|
|
@ -68,37 +73,12 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
|
|||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'entryPrice',
|
||||
header: 'Entry Price',
|
||||
id: 'price',
|
||||
header: 'Price',
|
||||
size: 100,
|
||||
cell: ({ getValue }) => {
|
||||
const price = getValue() as number;
|
||||
return (
|
||||
<span className="text-sm text-text-primary">
|
||||
${price != null ? price.toFixed(2) : '0.00'}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'exitDate',
|
||||
header: 'Exit Date',
|
||||
size: 180,
|
||||
cell: ({ getValue }) => {
|
||||
const date = getValue() as string | null;
|
||||
return (
|
||||
<span className="text-sm text-text-secondary">
|
||||
{date ? new Date(date).toLocaleString() : '-'}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'exitPrice',
|
||||
header: 'Exit Price',
|
||||
size: 100,
|
||||
cell: ({ getValue }) => {
|
||||
const price = getValue() as number;
|
||||
cell: ({ row }) => {
|
||||
const trade = row.original;
|
||||
const price = trade.price || trade.entryPrice;
|
||||
return (
|
||||
<span className="text-sm text-text-primary">
|
||||
${price != null ? price.toFixed(2) : '0.00'}
|
||||
|
|
@ -110,49 +90,83 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
|
|||
accessorKey: 'quantity',
|
||||
header: 'Quantity',
|
||||
size: 80,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="text-sm text-text-primary">{getValue() as number || 0}</span>
|
||||
),
|
||||
cell: ({ getValue }) => {
|
||||
const qty = Math.abs(getValue() as number || 0);
|
||||
return <span className="text-sm text-text-primary">{qty}</span>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'pnl',
|
||||
header: 'P&L',
|
||||
accessorKey: 'commission',
|
||||
header: 'Commission',
|
||||
size: 100,
|
||||
cell: ({ getValue }) => {
|
||||
const pnl = getValue() as number || 0;
|
||||
const commission = getValue() as number || 0;
|
||||
return (
|
||||
<span className={`text-sm font-medium ${
|
||||
pnl >= 0 ? 'text-success' : 'text-error'
|
||||
}`}>
|
||||
${pnl != null ? pnl.toFixed(2) : '0.00'}
|
||||
<span className="text-sm text-text-secondary">
|
||||
${commission.toFixed(2)}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'pnlPercent',
|
||||
header: 'P&L %',
|
||||
id: 'pnl',
|
||||
header: 'P&L',
|
||||
size: 100,
|
||||
cell: ({ getValue }) => {
|
||||
const pnlPercent = getValue() as number || 0;
|
||||
cell: ({ row }) => {
|
||||
const trade = row.original;
|
||||
const pnl = trade.pnl || trade.realizedPnl || 0;
|
||||
return (
|
||||
<span className={`text-sm font-medium ${
|
||||
pnlPercent >= 0 ? 'text-success' : 'text-error'
|
||||
pnl >= 0 ? 'text-success' : 'text-error'
|
||||
}`}>
|
||||
{pnlPercent != null ? pnlPercent.toFixed(2) : '0.00'}%
|
||||
${pnl.toFixed(2)}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// Calculate trade statistics
|
||||
const tradeStats = result.trades.reduce((stats: any, trade: any) => {
|
||||
const pnl = trade.pnl || trade.realizedPnl || 0;
|
||||
if (pnl > 0) {
|
||||
stats.wins++;
|
||||
stats.totalWin += pnl;
|
||||
} else if (pnl < 0) {
|
||||
stats.losses++;
|
||||
stats.totalLoss += Math.abs(pnl);
|
||||
}
|
||||
stats.totalPnL += pnl;
|
||||
return stats;
|
||||
}, { wins: 0, losses: 0, totalWin: 0, totalLoss: 0, totalPnL: 0 });
|
||||
|
||||
const winRate = result.trades.length > 0 ? (tradeStats.wins / result.trades.length) * 100 : 0;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-4">
|
||||
<h3 className="text-base font-medium text-text-primary">Trade History</h3>
|
||||
<p className="text-sm text-text-secondary mt-1">
|
||||
Total: {result.trades.length} trades
|
||||
</p>
|
||||
<div className="mb-4 grid grid-cols-1 md:grid-cols-5 gap-4">
|
||||
<div className="bg-surface-secondary rounded-lg border border-border p-3">
|
||||
<p className="text-xs text-text-secondary">Total Trades</p>
|
||||
<p className="text-lg font-medium text-text-primary">{result.trades.length}</p>
|
||||
</div>
|
||||
<div className="bg-surface-secondary rounded-lg border border-border p-3">
|
||||
<p className="text-xs text-text-secondary">Win Rate</p>
|
||||
<p className="text-lg font-medium text-text-primary">{winRate.toFixed(1)}%</p>
|
||||
</div>
|
||||
<div className="bg-surface-secondary rounded-lg border border-border p-3">
|
||||
<p className="text-xs text-text-secondary">Wins</p>
|
||||
<p className="text-lg font-medium text-success">{tradeStats.wins}</p>
|
||||
</div>
|
||||
<div className="bg-surface-secondary rounded-lg border border-border p-3">
|
||||
<p className="text-xs text-text-secondary">Losses</p>
|
||||
<p className="text-lg font-medium text-error">{tradeStats.losses}</p>
|
||||
</div>
|
||||
<div className="bg-surface-secondary rounded-lg border border-border p-3">
|
||||
<p className="text-xs text-text-secondary">Total P&L</p>
|
||||
<p className={`text-lg font-medium ${tradeStats.totalPnL >= 0 ? 'text-success' : 'text-error'}`}>
|
||||
${tradeStats.totalPnL.toFixed(2)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
|
|
|
|||
|
|
@ -1,89 +0,0 @@
|
|||
interface Position {
|
||||
symbol: string;
|
||||
quantity: number;
|
||||
averagePrice?: number;
|
||||
avgPrice?: number;
|
||||
currentPrice?: number;
|
||||
lastPrice?: number;
|
||||
}
|
||||
|
||||
interface CompactPositionsTableProps {
|
||||
positions: Position[];
|
||||
onExpand?: () => void;
|
||||
}
|
||||
|
||||
export function CompactPositionsTable({ positions, onExpand }: CompactPositionsTableProps) {
|
||||
if (positions.length === 0) {
|
||||
return (
|
||||
<div className="bg-surface-secondary rounded-lg border border-border p-4">
|
||||
<h3 className="text-sm font-medium text-text-primary mb-2">Open Positions</h3>
|
||||
<p className="text-sm text-text-secondary">No open positions</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const totalPnL = positions.reduce((sum, p) => {
|
||||
const quantity = p.quantity || 0;
|
||||
const avgPrice = p.averagePrice || p.avgPrice || 0;
|
||||
const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
|
||||
return sum + ((currentPrice - avgPrice) * quantity);
|
||||
}, 0);
|
||||
|
||||
return (
|
||||
<div className="bg-surface-secondary rounded-lg border border-border p-4">
|
||||
<div className="flex justify-between items-center mb-3">
|
||||
<h3 className="text-sm font-medium text-text-primary">
|
||||
Open Positions ({positions.length})
|
||||
</h3>
|
||||
<span className={`text-sm font-medium ${totalPnL >= 0 ? 'text-success' : 'text-error'}`}>
|
||||
P&L: ${totalPnL.toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{positions.slice(0, 8).map((position, index) => {
|
||||
const quantity = position.quantity || 0;
|
||||
const avgPrice = position.averagePrice || position.avgPrice || 0;
|
||||
const currentPrice = position.currentPrice || position.lastPrice || avgPrice;
|
||||
const side = quantity > 0 ? 'long' : 'short';
|
||||
const absQuantity = Math.abs(quantity);
|
||||
const pnl = (currentPrice - avgPrice) * quantity;
|
||||
const pnlPercent = avgPrice > 0 ? (pnl / (avgPrice * absQuantity)) * 100 : 0;
|
||||
|
||||
return (
|
||||
<div key={index} className="flex items-center justify-between py-1.5 px-2 rounded hover:bg-surface-tertiary transition-colors">
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className="text-sm font-medium text-text-primary">{position.symbol}</span>
|
||||
<span className={`text-xs px-1.5 py-0.5 rounded ${
|
||||
side === 'long' ? 'bg-success/20 text-success' : 'bg-error/20 text-error'
|
||||
}`}>
|
||||
{side.toUpperCase()}
|
||||
</span>
|
||||
<span className="text-xs text-text-secondary">
|
||||
{absQuantity} @ ${avgPrice.toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className="text-xs text-text-secondary">
|
||||
${currentPrice.toFixed(2)}
|
||||
</span>
|
||||
<span className={`text-xs font-medium ${pnl >= 0 ? 'text-success' : 'text-error'}`}>
|
||||
{pnlPercent >= 0 ? '+' : ''}{pnlPercent.toFixed(1)}%
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{positions.length > 8 && (
|
||||
<button
|
||||
onClick={onExpand}
|
||||
className="w-full text-xs text-primary-500 hover:text-primary-600 text-center pt-2 font-medium"
|
||||
>
|
||||
View all {positions.length} positions
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,67 +0,0 @@
|
|||
import type { Position } from '../types';
|
||||
|
||||
interface PositionsTableProps {
|
||||
positions: Position[];
|
||||
}
|
||||
|
||||
export function PositionsTable({ positions }: PositionsTableProps) {
|
||||
const formatCurrency = (value: number) => {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(value);
|
||||
};
|
||||
|
||||
const formatPnl = (value: number) => {
|
||||
const formatted = formatCurrency(Math.abs(value));
|
||||
return value >= 0 ? `+${formatted}` : `-${formatted}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border">
|
||||
<th className="text-left py-2 px-2 font-medium text-text-secondary">Symbol</th>
|
||||
<th className="text-right py-2 px-2 font-medium text-text-secondary">Quantity</th>
|
||||
<th className="text-right py-2 px-2 font-medium text-text-secondary">Avg Price</th>
|
||||
<th className="text-right py-2 px-2 font-medium text-text-secondary">Current</th>
|
||||
<th className="text-right py-2 px-2 font-medium text-text-secondary">P&L</th>
|
||||
<th className="text-right py-2 px-2 font-medium text-text-secondary">Unrealized</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{positions.map((position) => {
|
||||
const totalPnl = position.realizedPnl + position.unrealizedPnl;
|
||||
return (
|
||||
<tr key={position.symbol} className="border-b border-border hover:bg-surface-tertiary">
|
||||
<td className="py-2 px-2 font-medium text-text-primary">{position.symbol}</td>
|
||||
<td className="text-right py-2 px-2 text-text-primary">
|
||||
{position.quantity.toLocaleString()}
|
||||
</td>
|
||||
<td className="text-right py-2 px-2 text-text-primary">
|
||||
{formatCurrency(position.averagePrice)}
|
||||
</td>
|
||||
<td className="text-right py-2 px-2 text-text-primary">
|
||||
{formatCurrency(position.currentPrice)}
|
||||
</td>
|
||||
<td className={`text-right py-2 px-2 font-medium ${
|
||||
totalPnl >= 0 ? 'text-success' : 'text-error'
|
||||
}`}>
|
||||
{formatPnl(totalPnl)}
|
||||
</td>
|
||||
<td className={`text-right py-2 px-2 ${
|
||||
position.unrealizedPnl >= 0 ? 'text-success' : 'text-error'
|
||||
}`}>
|
||||
{formatPnl(position.unrealizedPnl)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,177 +0,0 @@
|
|||
import { DataTable } from '@/components/ui/DataTable';
|
||||
import type { ColumnDef } from '@tanstack/react-table';
|
||||
import type { Run } from '../services/backtestApiV2';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import {
|
||||
CheckCircleIcon,
|
||||
XCircleIcon,
|
||||
PauseIcon,
|
||||
PlayIcon,
|
||||
ClockIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
|
||||
interface RunsListProps {
|
||||
runs: Run[];
|
||||
currentRunId?: string;
|
||||
onSelectRun: (runId: string) => void;
|
||||
}
|
||||
|
||||
export function RunsList({ runs, currentRunId, onSelectRun }: RunsListProps) {
|
||||
const navigate = useNavigate();
|
||||
const { id: backtestId } = useParams<{ id: string }>();
|
||||
|
||||
const getStatusIcon = (status: Run['status']) => {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
return <CheckCircleIcon className="w-4 h-4 text-success" />;
|
||||
case 'failed':
|
||||
return <XCircleIcon className="w-4 h-4 text-error" />;
|
||||
case 'cancelled':
|
||||
return <XCircleIcon className="w-4 h-4 text-text-secondary" />;
|
||||
case 'running':
|
||||
return <PlayIcon className="w-4 h-4 text-primary-500" />;
|
||||
case 'paused':
|
||||
return <PauseIcon className="w-4 h-4 text-warning" />;
|
||||
case 'pending':
|
||||
return <ClockIcon className="w-4 h-4 text-text-secondary" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusLabel = (status: Run['status']) => {
|
||||
return status.charAt(0).toUpperCase() + status.slice(1);
|
||||
};
|
||||
|
||||
const formatDuration = (startedAt?: string, completedAt?: string) => {
|
||||
if (!startedAt) return '-';
|
||||
const start = new Date(startedAt).getTime();
|
||||
const end = completedAt ? new Date(completedAt).getTime() : Date.now();
|
||||
const duration = end - start;
|
||||
|
||||
const seconds = Math.floor(duration / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
|
||||
if (hours > 0) {
|
||||
return `${hours}h ${minutes % 60}m`;
|
||||
} else if (minutes > 0) {
|
||||
return `${minutes}m ${seconds % 60}s`;
|
||||
} else {
|
||||
return `${seconds}s`;
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnDef<Run>[] = [
|
||||
{
|
||||
accessorKey: 'runNumber',
|
||||
header: 'Run #',
|
||||
size: 80,
|
||||
cell: ({ getValue, row }) => (
|
||||
<span className={`text-sm font-medium ${row.original.id === currentRunId ? 'text-primary-500' : 'text-text-primary'}`}>
|
||||
#{getValue() as number}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'status',
|
||||
header: 'Status',
|
||||
size: 120,
|
||||
cell: ({ getValue }) => {
|
||||
const status = getValue() as Run['status'];
|
||||
return (
|
||||
<div className="flex items-center space-x-2">
|
||||
{getStatusIcon(status)}
|
||||
<span className="text-sm text-text-primary">{getStatusLabel(status)}</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'progress',
|
||||
header: 'Progress',
|
||||
size: 150,
|
||||
cell: ({ row }) => {
|
||||
const progress = row.original.progress;
|
||||
const status = row.original.status;
|
||||
|
||||
if (status === 'pending') return <span className="text-sm text-text-secondary">-</span>;
|
||||
|
||||
return (
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="flex-1 bg-surface-tertiary rounded-full h-2 overflow-hidden">
|
||||
<div
|
||||
className="bg-primary-500 h-2 transition-all duration-300"
|
||||
style={{ width: `${progress}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-xs text-text-secondary">{progress.toFixed(0)}%</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'speedMultiplier',
|
||||
header: 'Speed',
|
||||
size: 80,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="text-sm text-text-primary">{getValue() as number}x</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'startedAt',
|
||||
header: 'Started',
|
||||
size: 180,
|
||||
cell: ({ getValue }) => {
|
||||
const date = getValue() as string | undefined;
|
||||
return (
|
||||
<span className="text-sm text-text-secondary">
|
||||
{date ? new Date(date).toLocaleString() : '-'}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'duration',
|
||||
header: 'Duration',
|
||||
size: 100,
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-text-secondary">
|
||||
{formatDuration(row.original.startedAt, row.original.completedAt)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'error',
|
||||
header: 'Error',
|
||||
size: 200,
|
||||
cell: ({ getValue }) => {
|
||||
const error = getValue() as string | undefined;
|
||||
return error ? (
|
||||
<span className="text-sm text-error truncate" title={error}>{error}</span>
|
||||
) : (
|
||||
<span className="text-sm text-text-secondary">-</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
if (runs.length === 0) {
|
||||
return (
|
||||
<div className="bg-surface-secondary rounded-lg border border-border p-8 text-center">
|
||||
<p className="text-text-secondary">No runs yet. Create a new run to get started.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DataTable
|
||||
data={runs}
|
||||
columns={columns}
|
||||
onRowClick={(run) => {
|
||||
navigate(`/backtests/${backtestId}/run/${run.id}`);
|
||||
onSelectRun(run.id);
|
||||
}}
|
||||
className="bg-surface-secondary rounded-lg border border-border"
|
||||
height={400}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,139 +0,0 @@
|
|||
import type { Trade } from '../types';
|
||||
|
||||
interface TradeLogProps {
|
||||
trades: Trade[];
|
||||
}
|
||||
|
||||
export function TradeLog({ trades }: TradeLogProps) {
|
||||
const formatCurrency = (value: number) => {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(value);
|
||||
};
|
||||
|
||||
const formatTime = (timestamp: string) => {
|
||||
return new Date(timestamp).toLocaleString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
};
|
||||
|
||||
// Show latest trades first
|
||||
const sortedTrades = [...trades].reverse();
|
||||
|
||||
// Check if any trades have P&L
|
||||
const showPnLColumn = trades.some(t => t.pnl !== undefined);
|
||||
|
||||
// Determine the action type based on side and position change
|
||||
const getActionType = (trade: Trade): string => {
|
||||
const positionBefore = trade.positionAfter + (trade.side === 'buy' ? -trade.quantity : trade.quantity);
|
||||
|
||||
if (trade.side === 'buy') {
|
||||
// If we had a negative position (short) and buying reduces it, it's a COVER
|
||||
if (positionBefore < 0 && trade.positionAfter > positionBefore) {
|
||||
return 'COVER';
|
||||
}
|
||||
// Otherwise it's a BUY (opening or adding to long)
|
||||
return 'BUY';
|
||||
} else {
|
||||
// If we had a positive position (long) and selling reduces it, it's a SELL
|
||||
if (positionBefore > 0 && trade.positionAfter < positionBefore) {
|
||||
return 'SELL';
|
||||
}
|
||||
// Otherwise it's a SHORT (opening or adding to short)
|
||||
return 'SHORT';
|
||||
}
|
||||
};
|
||||
|
||||
// Get color for action type
|
||||
const getActionColor = (action: string): string => {
|
||||
switch (action) {
|
||||
case 'BUY':
|
||||
return 'bg-success/10 text-success';
|
||||
case 'SELL':
|
||||
return 'bg-error/10 text-error';
|
||||
case 'SHORT':
|
||||
return 'bg-warning/10 text-warning';
|
||||
case 'COVER':
|
||||
return 'bg-primary/10 text-primary';
|
||||
default:
|
||||
return 'bg-surface-tertiary text-text-secondary';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border">
|
||||
<th className="text-left py-2 px-3 font-medium text-text-secondary">Time</th>
|
||||
<th className="text-left py-2 px-3 font-medium text-text-secondary">Symbol</th>
|
||||
<th className="text-center py-2 px-3 font-medium text-text-secondary">Action</th>
|
||||
<th className="text-right py-2 px-3 font-medium text-text-secondary">Qty</th>
|
||||
<th className="text-right py-2 px-3 font-medium text-text-secondary">Price</th>
|
||||
<th className="text-right py-2 px-3 font-medium text-text-secondary">Value</th>
|
||||
<th className="text-right py-2 px-3 font-medium text-text-secondary">Position</th>
|
||||
<th className="text-right py-2 px-3 font-medium text-text-secondary">Comm.</th>
|
||||
{showPnLColumn && (
|
||||
<th className="text-right py-2 px-3 font-medium text-text-secondary">P&L</th>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sortedTrades.map((trade) => {
|
||||
const tradeValue = trade.quantity * trade.price;
|
||||
const actionType = getActionType(trade);
|
||||
return (
|
||||
<tr key={trade.id} className="border-b border-border hover:bg-surface-tertiary">
|
||||
<td className="py-2 px-3 text-text-muted whitespace-nowrap">
|
||||
{formatTime(trade.timestamp)}
|
||||
</td>
|
||||
<td className="py-2 px-3 font-medium text-text-primary">{trade.symbol}</td>
|
||||
<td className="text-center py-2 px-3">
|
||||
<span className={`inline-flex px-2 py-0.5 text-xs font-medium rounded ${getActionColor(actionType)}`}>
|
||||
{actionType}
|
||||
</span>
|
||||
</td>
|
||||
<td className="text-right py-2 px-3 text-text-primary">
|
||||
{trade.quantity.toLocaleString()}
|
||||
</td>
|
||||
<td className="text-right py-2 px-3 text-text-primary">
|
||||
{formatCurrency(trade.price)}
|
||||
</td>
|
||||
<td className="text-right py-2 px-3 text-text-primary">
|
||||
{formatCurrency(tradeValue)}
|
||||
</td>
|
||||
<td className={`text-right py-2 px-3 font-medium ${
|
||||
trade.positionAfter > 0 ? 'text-success' :
|
||||
trade.positionAfter < 0 ? 'text-error' :
|
||||
'text-text-muted'
|
||||
}`}>
|
||||
{trade.positionAfter > 0 ? '+' : ''}{trade.positionAfter.toLocaleString()}
|
||||
</td>
|
||||
<td className="text-right py-2 px-3 text-text-muted">
|
||||
{formatCurrency(trade.commission)}
|
||||
</td>
|
||||
{showPnLColumn && (
|
||||
<td className={`text-right py-2 px-3 font-medium ${
|
||||
trade.pnl !== undefined ? (trade.pnl >= 0 ? 'text-success' : 'text-error') : 'text-text-muted'
|
||||
}`}>
|
||||
{trade.pnl !== undefined ? (
|
||||
<>{trade.pnl >= 0 ? '+' : ''}{formatCurrency(trade.pnl)}</>
|
||||
) : (
|
||||
'-'
|
||||
)}
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,12 +1,11 @@
|
|||
export { BacktestConfiguration } from './BacktestConfiguration';
|
||||
export { BacktestControls } from './BacktestControls';
|
||||
export { BacktestResults } from './BacktestResults';
|
||||
export { MetricsCard } from './MetricsCard';
|
||||
export { PositionsTable } from './PositionsTable';
|
||||
export { TradeLog } from './TradeLog';
|
||||
export { RunsList } from './RunsList';
|
||||
export { RunsListWithMetrics } from './RunsListWithMetrics';
|
||||
export { CompactPerformanceMetrics } from './CompactPerformanceMetrics';
|
||||
export { CompactPositionsTable } from './CompactPositionsTable';
|
||||
export { PositionsSummary } from './PositionsSummary';
|
||||
export { ChartContainer } from './ChartContainer';
|
||||
export { ChartContainer } from './ChartContainer';
|
||||
export { BacktestChart } from './BacktestChart';
|
||||
export { BacktestMetrics } from './BacktestMetrics';
|
||||
export { BacktestPlayback } from './BacktestPlayback';
|
||||
export { BacktestTrades } from './BacktestTrades';
|
||||
export { RunControlsCompact } from './RunControlsCompact';
|
||||
Loading…
Add table
Add a link
Reference in a new issue