#!/usr/bin/env bun /** * Test the new trade history functionality */ import { TradingEngine } from '@stock-bot/core'; async function testTradeHistory() { console.log('Testing trade history functionality...\n'); // Create a trading engine in backtest mode const config = { startTime: Date.now() - 86400000, // 24 hours ago endTime: Date.now(), speedMultiplier: 1.0 }; const engine = new TradingEngine('backtest', config as any); console.log('Trading engine created in', engine.getMode(), 'mode'); console.log('Initial trade count:', engine.getTradeCount()); console.log('Initial closed trades:', engine.getClosedTradeCount()); // Simulate some trades console.log('\n--- Simulating trades ---'); // Buy 100 shares at $50 console.log('Processing BUY: 100 shares @ $50'); engine.processFillWithMetadata( 'AAPL', 50.0, 100, 'buy', 1.0, 'ORDER001', 'STRATEGY001' ); console.log('Trade count after buy:', engine.getTradeCount()); console.log('Closed trades after buy:', engine.getClosedTradeCount()); // Sell 50 shares at $55 console.log('\nProcessing SELL: 50 shares @ $55'); engine.processFillWithMetadata( 'AAPL', 55.0, 50, 'sell', 1.0, 'ORDER002', 'STRATEGY001' ); console.log('Trade count after partial sell:', engine.getTradeCount()); console.log('Closed trades after partial sell:', engine.getClosedTradeCount()); // Get closed trades const closedTradesJson = engine.getClosedTrades(); const closedTrades = JSON.parse(closedTradesJson); console.log('\n--- Closed Trades ---'); closedTrades.forEach((trade: any) => { console.log(`Trade ${trade.id}:`); console.log(` Symbol: ${trade.symbol}`); console.log(` Entry: ${trade.entry_price} @ ${new Date(trade.entry_time).toISOString()}`); console.log(` Exit: ${trade.exit_price} @ ${new Date(trade.exit_time).toISOString()}`); console.log(` Quantity: ${trade.quantity}`); console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnl_percent.toFixed(2)}%)`); console.log(` Duration: ${trade.duration_ms}ms`); }); // Sell remaining 50 shares at $52 console.log('\nProcessing SELL: 50 shares @ $52'); engine.processFillWithMetadata( 'AAPL', 52.0, 50, 'sell', 1.0, 'ORDER003', 'STRATEGY001' ); console.log('Trade count after full close:', engine.getTradeCount()); console.log('Closed trades after full close:', engine.getClosedTradeCount()); // Get all trade history const allTradesJson = engine.getTradeHistory(); const allTrades = JSON.parse(allTradesJson); console.log('\n--- All Trade History ---'); console.log(`Total trades executed: ${allTrades.length}`); allTrades.forEach((trade: any) => { console.log(`${trade.id}: ${trade.side} ${trade.quantity} ${trade.symbol} @ ${trade.price}`); }); // Get final P&L const [realizedPnl, unrealizedPnl] = engine.getTotalPnl(); console.log('\n--- Final P&L ---'); console.log(`Realized P&L: $${realizedPnl.toFixed(2)}`); console.log(`Unrealized P&L: $${unrealizedPnl.toFixed(2)}`); console.log('\n✅ Trade history test completed successfully!'); } testTradeHistory().catch(console.error);