Files
trading_bot_v3/test-price-monitor-basic.mjs
mindesbunister 7de3eaf7b8 feat: implement real-time price monitoring with automatic analysis triggering
New Features:
- Real-time price monitoring service with 5-minute update cycles
- Automatic analysis triggering when prices approach TP/SL levels (15%/25% thresholds)
- Comprehensive price monitoring UI component with live updates
- Integration with automation service for smart analysis scheduling
- PnL tracking and position status monitoring

- EventEmitter-based real-time updates
- CoinGecko API integration with rate limiting
- TP/SL approach detection with configurable thresholds
- Alert system for critical price movements
- Database integration for trade tracking

- Price monitor startup/shutdown with automation lifecycle
- Event listeners for TP_APPROACH, SL_APPROACH, CRITICAL alerts
- Automatic screenshot capture and AI analysis on price triggers
- Enhanced progress tracking for price-based analysis
- Intelligent analysis context with price movement data

- RealTimePriceMonitor component with live price display
- Trade monitoring cards with P&L and distance to TP/SL
- Active alerts panel with price threshold notifications
- Monitoring service controls (start/stop/force update)
- Integration with automation page for comprehensive oversight

- GET: Retrieve monitoring data, alerts, and current prices
- POST: Control monitoring service and force price updates
- Real-time data formatting and status management

- Comprehensive price monitor integration tests
- Basic functionality validation scripts
- API endpoint testing capabilities

This implements the user's request for real-time price monitoring with automatic analysis triggering when prices approach critical levels, providing enhanced oversight of active trading positions.
2025-07-21 10:31:49 +02:00

118 lines
4.3 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import priceMonitorService from './lib/price-monitor.js';
import { PriceFetcher } from './lib/price-fetcher.js';
async function testPriceMonitorBasic() {
console.log('🧪 Testing Basic Price Monitor Functionality...\n');
try {
// Test 1: Price fetcher integration
console.log('1⃣ Testing PriceFetcher integration...');
const priceFetcher = new PriceFetcher();
const solPrice = await priceFetcher.getPrice('SOL');
console.log(`SOL Price: $${solPrice}`);
console.log('✅ PriceFetcher working\n');
// Test 2: Price monitor initialization
console.log('2⃣ Testing price monitor initialization...');
const initialStatus = priceMonitorService.isMonitoring();
console.log(`Initial status: ${initialStatus ? 'Active' : 'Inactive'}`);
console.log('✅ Price monitor initialized\n');
// Test 3: Event listener setup
console.log('3⃣ Testing event listener setup...');
let eventReceived = false;
priceMonitorService.on('test_event', (data) => {
console.log('Event received:', data);
eventReceived = true;
});
priceMonitorService.emit('test_event', { test: 'data' });
// Wait for event
await new Promise(resolve => setTimeout(resolve, 100));
console.log(`Event test: ${eventReceived ? '✅ Success' : '❌ Failed'}\n`);
// Test 4: Start monitoring
console.log('4⃣ Testing start monitoring...');
await priceMonitorService.startMonitoring();
const monitoringStatus = priceMonitorService.isMonitoring();
console.log(`Monitoring status: ${monitoringStatus ? '✅ Active' : '❌ Inactive'}\n`);
// Test 5: Get monitoring data
console.log('5⃣ Testing get monitoring data...');
const monitoringData = await priceMonitorService.getMonitoringData();
console.log('Monitoring data structure:', {
hasTradesArray: Array.isArray(monitoringData.trades),
hasAlertsArray: Array.isArray(monitoringData.alerts),
hasPricesObject: typeof monitoringData.prices === 'object',
hasLastUpdated: !!monitoringData.lastUpdated,
monitoringActive: monitoringData.monitoringActive
});
console.log('✅ Monitoring data structure valid\n');
// Test 6: Price update simulation
console.log('6⃣ Testing price update simulation...');
let priceUpdateReceived = false;
priceMonitorService.on('price_update', (data) => {
console.log('Price update received:', data.symbol, data.price);
priceUpdateReceived = true;
});
// Manually trigger a price update for testing
priceMonitorService.emit('price_update', {
symbol: 'SOLUSD',
price: 189.50,
timestamp: new Date().toISOString()
});
await new Promise(resolve => setTimeout(resolve, 100));
console.log(`Price update test: ${priceUpdateReceived ? '✅ Success' : '❌ Failed'}\n`);
// Test 7: Stop monitoring
console.log('7⃣ Testing stop monitoring...');
await priceMonitorService.stopMonitoring();
const stoppedStatus = priceMonitorService.isMonitoring();
console.log(`Stopped status: ${stoppedStatus ? '❌ Still active' : '✅ Stopped'}\n`);
console.log('🎉 All basic price monitor tests completed successfully!');
return {
priceFetcher: !!solPrice,
initialization: true,
eventListeners: eventReceived,
startMonitoring: monitoringStatus,
monitoringData: !!monitoringData,
priceUpdates: priceUpdateReceived,
stopMonitoring: !stoppedStatus
};
} catch (error) {
console.error('❌ Basic test failed:', error);
console.error('Stack trace:', error.stack);
throw error;
}
}
// Run the test
if (import.meta.url === `file://${process.argv[1]}`) {
testPriceMonitorBasic()
.then((results) => {
console.log('\n📊 Test Results Summary:');
Object.entries(results).forEach(([test, passed]) => {
console.log(` ${test}: ${passed ? '✅' : '❌'}`);
});
const allPassed = Object.values(results).every(result => result);
console.log(`\nOverall: ${allPassed ? '✅ All tests passed' : '❌ Some tests failed'}`);
process.exit(allPassed ? 0 : 1);
})
.catch((error) => {
console.error('\n❌ Test suite failed:', error.message);
process.exit(1);
});
}
export { testPriceMonitorBasic };