New Features: - 📊 Detailed Market Analysis Panel (similar to pro trading interface) * Market sentiment, recommendation, resistance/support levels * Detailed trading setup with entry/exit points * Risk management with R:R ratios and confirmation triggers * Technical indicators (RSI, OBV, VWAP) analysis - 🧠 AI Learning Insights Panel * Real-time learning status and success rates * Winner/Loser trade outcome tracking * AI reflection messages explaining what was learned * Current thresholds and pattern recognition data - 🔮 AI Database Integration * Shows what AI learned from previous trades * Current confidence thresholds and risk parameters * Pattern recognition for symbol/timeframe combinations * Next trade adjustments based on learning - 🎓 Intelligent Learning from Outcomes * Automatic trade outcome analysis (winner/loser) * AI generates learning insights from each trade result * Confidence adjustment based on trade performance * Pattern reinforcement or correction based on results - Beautiful gradient panels with color-coded sections - Clear winner/loser indicators with visual feedback - Expandable detailed analysis view - Real-time learning progress tracking - Completely isolated paper trading (no real money risk) - Real market data integration for authentic learning - Safe practice environment with professional analysis tools This provides a complete AI learning trading simulation where users can: 1. Get real market analysis with detailed reasoning 2. Execute safe paper trades with zero risk 3. See immediate feedback on trade outcomes 4. Learn from AI reflections and insights 5. Understand how AI adapts and improves over time
248 lines
8.9 KiB
JavaScript
248 lines
8.9 KiB
JavaScript
#!/usr/bin/env node
|
|
|
|
/**
|
|
* Test Enhanced Paper Trading System
|
|
* Tests the new anti-chasing system integration with paper trading
|
|
*/
|
|
|
|
const BASE_URL = 'http://localhost:9001'
|
|
|
|
async function testPaperTradingSystem() {
|
|
console.log('🧪 Testing Enhanced Paper Trading System')
|
|
console.log('=' .repeat(60))
|
|
|
|
const testSymbol = 'SOLUSD'
|
|
const testTimeframe = '240' // 4H for less noise
|
|
const testBalance = 1000 // $1000 paper balance
|
|
|
|
console.log(`📊 Test Parameters:`)
|
|
console.log(` Symbol: ${testSymbol}`)
|
|
console.log(` Timeframe: ${testTimeframe} (4H)`)
|
|
console.log(` Paper Balance: $${testBalance}`)
|
|
console.log('')
|
|
|
|
try {
|
|
// Test 1: Enhanced Anti-Chasing Analysis
|
|
console.log('🛡️ Test 1: Enhanced Anti-Chasing Analysis')
|
|
console.log('-'.repeat(40))
|
|
|
|
const analysisStart = Date.now()
|
|
const analysisResponse = await fetch(`${BASE_URL}/api/enhanced-anti-chasing`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
symbol: testSymbol,
|
|
timeframe: testTimeframe,
|
|
layouts: ['ai', 'diy'],
|
|
currentBalance: testBalance
|
|
})
|
|
})
|
|
|
|
const analysisTime = Date.now() - analysisStart
|
|
console.log(`⏱️ Analysis completed in ${(analysisTime / 1000).toFixed(1)}s`)
|
|
|
|
if (!analysisResponse.ok) {
|
|
const errorText = await analysisResponse.text()
|
|
console.error('❌ Analysis failed:', errorText)
|
|
return
|
|
}
|
|
|
|
const analysisData = await analysisResponse.json()
|
|
const analysis = analysisData.data?.analysis
|
|
const riskAssessment = analysisData.data?.riskAssessment
|
|
const tradeDecision = analysisData.data?.tradeDecision
|
|
const antiChasingInsights = analysisData.data?.antiChasingInsights
|
|
|
|
if (!analysis) {
|
|
console.error('❌ No analysis data received')
|
|
return
|
|
}
|
|
|
|
console.log('✅ Analysis Results:')
|
|
console.log(` Recommendation: ${analysis.recommendation}`)
|
|
console.log(` Confidence: ${analysis.confidence}%`)
|
|
console.log(` Momentum Status: ${analysis.momentumStatus?.type || 'Unknown'}`)
|
|
console.log(` Entry Quality: ${analysis.entryQuality?.score || 'N/A'}/100`)
|
|
console.log(` Risk Level: ${analysis.entryQuality?.riskLevel || 'Unknown'}`)
|
|
|
|
if (analysis.entry) {
|
|
console.log(` Entry Price: $${analysis.entry.price}`)
|
|
}
|
|
if (analysis.stopLoss) {
|
|
console.log(` Stop Loss: $${analysis.stopLoss.price}`)
|
|
}
|
|
if (analysis.takeProfits?.tp1) {
|
|
console.log(` Take Profit: $${analysis.takeProfits.tp1.price}`)
|
|
}
|
|
if (analysis.riskToReward) {
|
|
console.log(` Risk:Reward Ratio: ${analysis.riskToReward}`)
|
|
}
|
|
|
|
console.log('')
|
|
|
|
// Test 2: Risk Management Assessment
|
|
if (riskAssessment) {
|
|
console.log('⚖️ Test 2: Risk Assessment')
|
|
console.log('-'.repeat(40))
|
|
console.log(` Risk Level: ${riskAssessment.riskLevel || 'Unknown'}`)
|
|
console.log(` Recommended Size: $${riskAssessment.recommendedSize || 'N/A'}`)
|
|
console.log(` Max Loss: $${riskAssessment.maxLoss || 'N/A'}`)
|
|
console.log(` Position Limit: ${riskAssessment.positionLimit || 'N/A'}%`)
|
|
|
|
if (riskAssessment.riskWarnings?.length > 0) {
|
|
console.log(' Risk Warnings:')
|
|
riskAssessment.riskWarnings.forEach(warning => {
|
|
console.log(` ⚠️ ${warning}`)
|
|
})
|
|
}
|
|
console.log('')
|
|
}
|
|
|
|
// Test 3: Trade Decision Logic
|
|
if (tradeDecision) {
|
|
console.log('🎯 Test 3: Trade Decision')
|
|
console.log('-'.repeat(40))
|
|
console.log(` Trade Allowed: ${tradeDecision.allowed ? '✅ YES' : '❌ NO'}`)
|
|
console.log(` Decision Reason: ${tradeDecision.reason}`)
|
|
|
|
if (tradeDecision.confidenceRequired) {
|
|
console.log(` Confidence Required: ≥${tradeDecision.confidenceRequired}%`)
|
|
console.log(` Actual Confidence: ${tradeDecision.actualConfidence}%`)
|
|
}
|
|
|
|
if (tradeDecision.qualityRequired) {
|
|
console.log(` Quality Required: ≥${tradeDecision.qualityRequired}/100`)
|
|
console.log(` Actual Quality: ${tradeDecision.actualQuality}/100`)
|
|
}
|
|
console.log('')
|
|
}
|
|
|
|
// Test 4: Anti-Chasing Insights
|
|
if (antiChasingInsights) {
|
|
console.log('🛡️ Test 4: Anti-Chasing Insights')
|
|
console.log('-'.repeat(40))
|
|
|
|
if (antiChasingInsights.momentumAnalysis) {
|
|
const momentum = antiChasingInsights.momentumAnalysis
|
|
console.log(` Momentum Type: ${momentum.type}`)
|
|
console.log(` Momentum Direction: ${momentum.direction}`)
|
|
console.log(` Reversal Probability: ${momentum.reversalProbability || 'N/A'}%`)
|
|
console.log(` Strength: ${momentum.strength || 'N/A'}`)
|
|
}
|
|
|
|
if (antiChasingInsights.timeframeAlignment) {
|
|
console.log(` Timeframe Alignment: ${antiChasingInsights.timeframeAlignment.alignment}`)
|
|
}
|
|
|
|
if (antiChasingInsights.preventedChasing) {
|
|
console.log(' 🛡️ Anti-Chasing: Prevented momentum chasing!')
|
|
}
|
|
|
|
console.log('')
|
|
}
|
|
|
|
// Test 5: Paper Trading Simulation
|
|
console.log('📄 Test 5: Paper Trading Simulation')
|
|
console.log('-'.repeat(40))
|
|
|
|
if (analysis.recommendation !== 'HOLD' && tradeDecision?.allowed) {
|
|
console.log('✅ Simulating paper trade execution...')
|
|
|
|
const paperTrade = {
|
|
id: Date.now(),
|
|
timestamp: new Date().toISOString(),
|
|
symbol: testSymbol,
|
|
timeframe: testTimeframe,
|
|
side: analysis.recommendation,
|
|
entryPrice: analysis.entry?.price || 100,
|
|
stopLoss: analysis.stopLoss?.price,
|
|
takeProfit: analysis.takeProfits?.tp1?.price,
|
|
confidence: analysis.confidence,
|
|
reasoning: analysis.reasoning,
|
|
riskReward: analysis.riskToReward,
|
|
momentumStatus: analysis.momentumStatus?.type,
|
|
entryQuality: analysis.entryQuality?.score,
|
|
status: 'OPEN'
|
|
}
|
|
|
|
// Calculate position size based on risk management
|
|
const riskAmount = testBalance * 0.01 // 1% risk
|
|
const stopDistance = Math.abs(paperTrade.entryPrice - (paperTrade.stopLoss || paperTrade.entryPrice * 0.95))
|
|
paperTrade.positionSize = Math.min(riskAmount / stopDistance, testBalance * 0.1)
|
|
|
|
console.log(` Paper Trade Details:`)
|
|
console.log(` Action: ${paperTrade.side} ${paperTrade.symbol}`)
|
|
console.log(` Entry: $${paperTrade.entryPrice}`)
|
|
console.log(` Stop Loss: $${paperTrade.stopLoss || 'N/A'}`)
|
|
console.log(` Take Profit: $${paperTrade.takeProfit || 'N/A'}`)
|
|
console.log(` Position Size: $${paperTrade.positionSize.toFixed(2)}`)
|
|
console.log(` Risk Amount: $${riskAmount.toFixed(2)}`)
|
|
console.log(` Confidence: ${paperTrade.confidence}%`)
|
|
console.log(` Entry Quality: ${paperTrade.entryQuality}/100`)
|
|
console.log(` Momentum: ${paperTrade.momentumStatus}`)
|
|
|
|
} else {
|
|
console.log(`❌ No trade executed`)
|
|
console.log(` Reason: ${analysis.recommendation === 'HOLD' ? 'HOLD recommendation' : 'Trade rejected by risk management'}`)
|
|
}
|
|
|
|
console.log('')
|
|
console.log('🎉 Paper Trading System Test Complete!')
|
|
console.log('=' .repeat(60))
|
|
|
|
// Summary
|
|
console.log('📋 Test Summary:')
|
|
console.log(` ✅ Enhanced Analysis: Working`)
|
|
console.log(` ✅ Anti-Chasing Logic: ${antiChasingInsights ? 'Active' : 'Unknown'}`)
|
|
console.log(` ✅ Risk Management: ${riskAssessment ? 'Active' : 'Unknown'}`)
|
|
console.log(` ✅ Trade Decision: ${tradeDecision ? 'Working' : 'Unknown'}`)
|
|
console.log(` ✅ Paper Trading: Ready`)
|
|
console.log(` ⏱️ Total Time: ${(Date.now() - analysisStart) / 1000}s`)
|
|
|
|
} catch (error) {
|
|
console.error('❌ Test failed:', error.message)
|
|
console.error('Stack trace:', error.stack)
|
|
}
|
|
}
|
|
|
|
// Test if we can reach the API first
|
|
async function testConnection() {
|
|
try {
|
|
console.log('🔗 Testing connection to trading bot...')
|
|
const response = await fetch(`${BASE_URL}/api/status`)
|
|
|
|
if (response.ok) {
|
|
const data = await response.json()
|
|
console.log('✅ Connection successful')
|
|
console.log(` Container Status: Running`)
|
|
console.log(` API Accessible: Yes`)
|
|
console.log('')
|
|
return true
|
|
} else {
|
|
console.error('❌ API not responding properly')
|
|
return false
|
|
}
|
|
} catch (error) {
|
|
console.error('❌ Connection failed:', error.message)
|
|
console.error(' Make sure the trading bot container is running on port 9001')
|
|
console.error(' Run: npm run docker:dev')
|
|
return false
|
|
}
|
|
}
|
|
|
|
// Main execution
|
|
async function main() {
|
|
console.log('🧪 Enhanced Paper Trading Test Suite')
|
|
console.log('Testing new anti-chasing system integration')
|
|
console.log('=' .repeat(60))
|
|
|
|
const connected = await testConnection()
|
|
if (!connected) {
|
|
process.exit(1)
|
|
}
|
|
|
|
await testPaperTradingSystem()
|
|
}
|
|
|
|
main().catch(console.error)
|