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
424 lines
13 KiB
TypeScript
424 lines
13 KiB
TypeScript
import OpenAI from 'openai'
|
|
import fs from 'fs/promises'
|
|
import path from 'path'
|
|
|
|
const openai = new OpenAI({
|
|
apiKey: process.env.OPENAI_API_KEY,
|
|
})
|
|
|
|
export interface EnhancedAnalysisResult {
|
|
summary: string
|
|
marketSentiment: 'BULLISH' | 'BEARISH' | 'NEUTRAL'
|
|
keyLevels: {
|
|
support: number[]
|
|
resistance: number[]
|
|
}
|
|
recommendation: 'BUY' | 'SELL' | 'HOLD'
|
|
confidence: number // 0-100
|
|
reasoning: string
|
|
|
|
// Enhanced Anti-Chasing Analysis
|
|
momentumStatus: {
|
|
type: 'BUILDING' | 'EXHAUSTED' | 'NEUTRAL'
|
|
direction: 'UP' | 'DOWN' | 'SIDEWAYS'
|
|
exhaustionSignals: string[]
|
|
reversalProbability: number // 0-100
|
|
}
|
|
|
|
// Multi-Timeframe Validation
|
|
timeframeAlignment: {
|
|
trend: '4H' | '1H' | '15M' // Primary trend timeframe
|
|
alignment: 'STRONG' | 'WEAK' | 'CONFLICTED'
|
|
conflictWarnings: string[]
|
|
}
|
|
|
|
// Enhanced Entry Conditions
|
|
entryQuality: {
|
|
score: number // 0-100
|
|
requiredConfirmations: string[]
|
|
missingConfirmations: string[]
|
|
riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'EXTREME'
|
|
}
|
|
|
|
// Risk-Adjusted Trading Levels
|
|
entry?: {
|
|
price: number
|
|
buffer?: string
|
|
rationale: string
|
|
timeframeRisk: 'LOW' | 'MEDIUM' | 'HIGH'
|
|
}
|
|
stopLoss?: {
|
|
price: number
|
|
rationale: string
|
|
atrMultiple: number // ATR-based stop calculation
|
|
}
|
|
takeProfits?: {
|
|
tp1?: {
|
|
price: number
|
|
description: string
|
|
probabilityReach: number // 0-100
|
|
}
|
|
tp2?: {
|
|
price: number
|
|
description: string
|
|
probabilityReach: number // 0-100
|
|
}
|
|
}
|
|
riskToReward?: string
|
|
|
|
// Advanced Confirmations
|
|
confirmationTrigger?: string
|
|
invalidationLevel?: number
|
|
|
|
// Position Sizing Guidance
|
|
positionSizing?: {
|
|
riskPercentage: number // Recommended risk per trade
|
|
maxPositionSize: number // Maximum recommended position
|
|
volatilityAdjustment: number // Adjustment for current volatility
|
|
}
|
|
}
|
|
|
|
export class EnhancedAntiChasingAI {
|
|
|
|
async analyzeWithAntiChasing(filenameOrPath: string): Promise<EnhancedAnalysisResult | null> {
|
|
try {
|
|
let imagePath: string
|
|
|
|
if (path.isAbsolute(filenameOrPath)) {
|
|
imagePath = filenameOrPath
|
|
} else {
|
|
const screenshotsDir = path.join(process.cwd(), 'screenshots')
|
|
imagePath = path.join(screenshotsDir, filenameOrPath)
|
|
}
|
|
|
|
const imageBuffer = await fs.readFile(imagePath)
|
|
const base64Image = imageBuffer.toString('base64')
|
|
|
|
const prompt = `You are an expert trading analyst specializing in ANTI-MOMENTUM CHASING and HIGH-PROBABILITY setups. Your goal is to prevent losses from entering trades after momentum has exhausted.
|
|
|
|
**CRITICAL MISSION: PREVENT MOMENTUM CHASING LOSSES**
|
|
|
|
Your analysis must focus on:
|
|
1. **MOMENTUM EXHAUSTION DETECTION** - Identify when moves are ENDING, not beginning
|
|
2. **MULTI-TIMEFRAME VALIDATION** - Ensure all timeframes agree before entry
|
|
3. **HIGH-PROBABILITY REVERSALS** - Only recommend trades with strong reversal signals
|
|
4. **RISK-ADJUSTED ENTRIES** - Match position size to timeframe risk
|
|
|
|
**ANTI-CHASING METHODOLOGY:**
|
|
|
|
**MOMENTUM EXHAUSTION SIGNALS:**
|
|
- **RSI DIVERGENCE**: Price making new highs/lows but RSI showing divergence
|
|
- **VOLUME EXHAUSTION**: Decreasing volume on continued price movement
|
|
- **CANDLE PATTERNS**: Doji, shooting stars, hammers at key levels
|
|
- **MULTIPLE REJECTIONS**: 2+ rejections at support/resistance
|
|
- **OVEREXTENSION**: Price far from moving averages (>2 ATR)
|
|
|
|
**TIMEFRAME RISK ASSESSMENT:**
|
|
- **15M Charts**: HIGH RISK - Require 85%+ confidence, tight stops
|
|
- **1H Charts**: MEDIUM RISK - Require 80%+ confidence, moderate stops
|
|
- **4H Charts**: LOW RISK - Require 75%+ confidence, wider stops
|
|
- **Daily Charts**: LOWEST RISK - Require 70%+ confidence, structural stops
|
|
|
|
**ENTRY QUALITY CHECKLIST:**
|
|
✅ **Momentum Exhausted**: Not chasing active moves
|
|
✅ **Multiple Confirmations**: 3+ indicators agree
|
|
✅ **Structure Support**: Near key support/resistance
|
|
✅ **Volume Confirmation**: Volume supports the setup
|
|
✅ **Risk/Reward**: Minimum 1:2 ratio
|
|
✅ **Invalidation Clear**: Know exactly when wrong
|
|
|
|
**FORBIDDEN SETUPS (NEVER RECOMMEND):**
|
|
❌ **Chasing Breakouts**: Price already moved >2% rapidly
|
|
❌ **FOMO Entries**: Strong moves without pullbacks
|
|
❌ **Single Indicator**: Only one confirmation signal
|
|
❌ **Against Trend**: Counter-trend without clear reversal
|
|
❌ **Poor R:R**: Risk/Reward worse than 1:2
|
|
❌ **Unclear Stops**: No obvious stop loss level
|
|
|
|
**ANALYSIS PROCESS:**
|
|
|
|
1. **IDENTIFY MOMENTUM STATE**:
|
|
- Is momentum BUILDING (early in move) or EXHAUSTED (late in move)?
|
|
- Look for divergences, volume patterns, overextension
|
|
|
|
2. **CHECK TIMEFRAME ALIGNMENT**:
|
|
- Do multiple timeframes agree on direction?
|
|
- Is this the right timeframe for this setup?
|
|
|
|
3. **VALIDATE ENTRY QUALITY**:
|
|
- Count confirmation signals (need 3+ for entry)
|
|
- Assess risk level and position sizing needs
|
|
|
|
4. **CALCULATE RISK-ADJUSTED LEVELS**:
|
|
- Entry: Based on structure and confirmation
|
|
- Stop Loss: ATR-based, below/above key structure
|
|
- Take Profit: Conservative targets with high probability
|
|
|
|
**RESPONSE FORMAT** (JSON only):
|
|
|
|
{
|
|
"summary": "Anti-chasing analysis focusing on momentum exhaustion and high-probability setups",
|
|
"marketSentiment": "BULLISH|BEARISH|NEUTRAL",
|
|
"keyLevels": {
|
|
"support": [visible support levels],
|
|
"resistance": [visible resistance levels]
|
|
},
|
|
"recommendation": "BUY|SELL|HOLD",
|
|
"confidence": 75,
|
|
"reasoning": "Detailed reasoning focusing on momentum state and entry quality",
|
|
|
|
"momentumStatus": {
|
|
"type": "BUILDING|EXHAUSTED|NEUTRAL",
|
|
"direction": "UP|DOWN|SIDEWAYS",
|
|
"exhaustionSignals": ["List specific exhaustion signals seen"],
|
|
"reversalProbability": 65
|
|
},
|
|
|
|
"timeframeAlignment": {
|
|
"trend": "4H|1H|15M",
|
|
"alignment": "STRONG|WEAK|CONFLICTED",
|
|
"conflictWarnings": ["Any timeframe conflicts"]
|
|
},
|
|
|
|
"entryQuality": {
|
|
"score": 85,
|
|
"requiredConfirmations": ["List of confirmations present"],
|
|
"missingConfirmations": ["List of missing confirmations"],
|
|
"riskLevel": "LOW|MEDIUM|HIGH|EXTREME"
|
|
},
|
|
|
|
"entry": {
|
|
"price": 150.50,
|
|
"buffer": "±0.25",
|
|
"rationale": "Entry based on exhaustion signals and structure",
|
|
"timeframeRisk": "LOW|MEDIUM|HIGH"
|
|
},
|
|
|
|
"stopLoss": {
|
|
"price": 148.00,
|
|
"rationale": "Stop below key structure level",
|
|
"atrMultiple": 1.5
|
|
},
|
|
|
|
"takeProfits": {
|
|
"tp1": {
|
|
"price": 152.00,
|
|
"description": "Conservative target at structure",
|
|
"probabilityReach": 75
|
|
},
|
|
"tp2": {
|
|
"price": 154.00,
|
|
"description": "Extended target if momentum continues",
|
|
"probabilityReach": 45
|
|
}
|
|
},
|
|
|
|
"riskToReward": "1:2.5",
|
|
"confirmationTrigger": "Wait for specific confirmation before entry",
|
|
"invalidationLevel": 149.00,
|
|
|
|
"positionSizing": {
|
|
"riskPercentage": 1.0,
|
|
"maxPositionSize": 10,
|
|
"volatilityAdjustment": 0.8
|
|
}
|
|
}
|
|
|
|
**CRITICAL REQUIREMENTS:**
|
|
- If momentum appears to be chasing, recommend HOLD regardless of other signals
|
|
- Require minimum 3 confirmations for any BUY/SELL recommendation
|
|
- Always provide clear invalidation levels
|
|
- Match position sizing to timeframe risk
|
|
- Focus on HIGH-PROBABILITY setups only
|
|
|
|
Analyze the chart with EXTREME FOCUS on preventing momentum chasing losses.`
|
|
|
|
const response = await openai.chat.completions.create({
|
|
model: "gpt-4o-mini",
|
|
messages: [
|
|
{
|
|
role: "user",
|
|
content: [
|
|
{ type: "text", text: prompt },
|
|
{
|
|
type: "image_url",
|
|
image_url: {
|
|
url: `data:image/png;base64,${base64Image}`,
|
|
detail: "high"
|
|
}
|
|
}
|
|
]
|
|
}
|
|
],
|
|
max_tokens: 2000,
|
|
temperature: 0.1
|
|
})
|
|
|
|
const content = response.choices[0]?.message?.content
|
|
if (!content) return null
|
|
|
|
console.log('🛡️ Anti-chasing AI response:', content.substring(0, 200) + '...')
|
|
|
|
// Extract JSON from response
|
|
const match = content.match(/\{[\s\S]*\}/)
|
|
if (!match) {
|
|
console.error('No JSON found in anti-chasing response')
|
|
return null
|
|
}
|
|
|
|
const json = match[0]
|
|
const result = JSON.parse(json)
|
|
|
|
// Validate anti-chasing requirements
|
|
if (result.entryQuality?.score < 70) {
|
|
console.log('⚠️ Entry quality too low - overriding to HOLD')
|
|
result.recommendation = 'HOLD'
|
|
result.reasoning = `Entry quality score ${result.entryQuality.score} is below minimum threshold. ${result.reasoning}`
|
|
}
|
|
|
|
if (result.momentumStatus?.type === 'EXHAUSTED' && result.confidence > 80) {
|
|
console.log('✅ High-quality exhaustion setup detected')
|
|
} else if (result.momentumStatus?.type === 'BUILDING') {
|
|
console.log('⚠️ Potential momentum chasing detected - increasing requirements')
|
|
result.confidence = Math.max(0, result.confidence - 20)
|
|
}
|
|
|
|
return result as EnhancedAnalysisResult
|
|
|
|
} catch (error) {
|
|
console.error('❌ Enhanced anti-chasing analysis failed:', error)
|
|
return null
|
|
}
|
|
}
|
|
|
|
async analyzeMultipleWithAntiChasing(filenamesOrPaths: string[]): Promise<EnhancedAnalysisResult | null> {
|
|
try {
|
|
// Read all image files and convert to base64
|
|
const images = await Promise.all(
|
|
filenamesOrPaths.map(async (filenameOrPath) => {
|
|
let imagePath: string
|
|
|
|
if (path.isAbsolute(filenameOrPath)) {
|
|
imagePath = filenameOrPath
|
|
} else {
|
|
const screenshotsDir = path.join(process.cwd(), 'screenshots')
|
|
imagePath = path.join(screenshotsDir, filenameOrPath)
|
|
}
|
|
|
|
const imageBuffer = await fs.readFile(imagePath)
|
|
const base64Image = imageBuffer.toString('base64')
|
|
return {
|
|
type: "image_url" as const,
|
|
image_url: {
|
|
url: `data:image/png;base64,${base64Image}`,
|
|
detail: "high" as const
|
|
}
|
|
}
|
|
})
|
|
)
|
|
|
|
const timeframeInfo = filenamesOrPaths.map(f => {
|
|
const filename = path.basename(f)
|
|
if (filename.includes('240')) return '4H'
|
|
if (filename.includes('60')) return '1H'
|
|
if (filename.includes('15')) return '15M'
|
|
return 'Unknown'
|
|
}).join(', ')
|
|
|
|
const prompt = `You are analyzing ${filenamesOrPaths.length} charts (${timeframeInfo}) with ANTI-MOMENTUM CHASING focus.
|
|
|
|
**MISSION: PREVENT MOMENTUM CHASING ACROSS MULTIPLE TIMEFRAMES**
|
|
|
|
**MULTI-TIMEFRAME ANTI-CHASING RULES:**
|
|
|
|
1. **TIMEFRAME HIERARCHY**:
|
|
- 4H: Primary trend direction (most important)
|
|
- 1H: Entry confirmation and timing
|
|
- 15M: Precise entry point and quick confirmations
|
|
|
|
2. **ALIGNMENT REQUIREMENTS**:
|
|
- ALL timeframes must agree on direction for entry
|
|
- Higher timeframes override lower timeframes
|
|
- If conflict exists, recommend HOLD
|
|
|
|
3. **MOMENTUM EXHAUSTION VALIDATION**:
|
|
- Check each timeframe for exhaustion signals
|
|
- Look for divergences across timeframes
|
|
- Ensure not chasing moves on any timeframe
|
|
|
|
4. **MULTI-TIMEFRAME CONFIRMATION**:
|
|
- Need confirmation on AT LEAST 2 timeframes
|
|
- Higher timeframe structure + lower timeframe entry
|
|
- Volume confirmation across timeframes
|
|
|
|
**ANALYSIS REQUIREMENTS:**
|
|
|
|
For each timeframe:
|
|
- Identify momentum state (building/exhausted/neutral)
|
|
- Check for exhaustion signals and reversals
|
|
- Validate entry quality and confirmations
|
|
- Assess risk level for that timeframe
|
|
|
|
Cross-timeframe validation:
|
|
- Ensure no conflicts between timeframes
|
|
- Confirm entry timing on appropriate timeframe
|
|
- Validate stop loss placement across timeframes
|
|
|
|
**FORBIDDEN MULTI-TIMEFRAME SETUPS:**
|
|
❌ Timeframes pointing in different directions
|
|
❌ Chasing momentum on any timeframe
|
|
❌ Entry without multi-timeframe confirmation
|
|
❌ Risk/reward not suitable for highest timeframe
|
|
|
|
Provide comprehensive multi-timeframe anti-chasing analysis in the same JSON format, with additional focus on timeframe alignment and cross-validation.`
|
|
|
|
const messages = [
|
|
{
|
|
role: "user" as const,
|
|
content: [
|
|
{ type: "text" as const, text: prompt },
|
|
...images
|
|
]
|
|
}
|
|
]
|
|
|
|
console.log(`🛡️ Analyzing ${filenamesOrPaths.length} timeframes with anti-chasing focus...`)
|
|
|
|
const response = await openai.chat.completions.create({
|
|
model: "gpt-4o-mini",
|
|
messages,
|
|
max_tokens: 2500,
|
|
temperature: 0.1
|
|
})
|
|
|
|
const content = response.choices[0]?.message?.content
|
|
if (!content) {
|
|
throw new Error('No response from OpenAI')
|
|
}
|
|
|
|
const jsonMatch = content.match(/\{[\s\S]*\}/)
|
|
if (!jsonMatch) {
|
|
throw new Error('No JSON found in multi-timeframe response')
|
|
}
|
|
|
|
const analysis = JSON.parse(jsonMatch[0])
|
|
|
|
// Enhanced validation for multi-timeframe
|
|
if (analysis.timeframeAlignment?.alignment === 'CONFLICTED') {
|
|
console.log('⚠️ Timeframe conflict detected - overriding to HOLD')
|
|
analysis.recommendation = 'HOLD'
|
|
analysis.confidence = Math.min(analysis.confidence, 40)
|
|
}
|
|
|
|
console.log('✅ Multi-timeframe anti-chasing analysis complete')
|
|
return analysis as EnhancedAnalysisResult
|
|
|
|
} catch (error: any) {
|
|
console.error('❌ Multi-timeframe anti-chasing analysis failed:', error.message)
|
|
return null
|
|
}
|
|
}
|
|
}
|
|
|
|
export const enhancedAntiChasingAI = new EnhancedAntiChasingAI()
|