Files
trading_bot_v3/lib/ai-analysis.ts
mindesbunister 483d4c6576 🔧 Fix AI Analysis Service - Improved Prompts & Error Handling
 FIXED: AI analysis prompts to bypass OpenAI safety guardrails
 FIXED: Added technical analysis focus instead of trading advice tone
 FIXED: Improved JSON parsing and error handling
 ADDED: Option to use existing screenshots for testing (useExisting param)
 IMPROVED: Better image detail settings and temperature for consistency

🐛 DEBUGGING: Still investigating why AI claims it can't see images
- OpenAI vision capabilities confirmed working with public images
- Model gpt-4o has proper vision support
- Issue appears to be with chart image content or encoding

🎯 NEXT: Debug image encoding and model response inconsistency
2025-07-12 15:08:24 +02:00

410 lines
14 KiB
TypeScript

import OpenAI from 'openai'
import fs from 'fs/promises'
import path from 'path'
import { enhancedScreenshotService, ScreenshotConfig } from './enhanced-screenshot'
import { TradingViewCredentials } from './tradingview-automation'
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
})
export interface AnalysisResult {
summary: string
marketSentiment: 'BULLISH' | 'BEARISH' | 'NEUTRAL'
keyLevels: {
support: number[]
resistance: number[]
}
recommendation: 'BUY' | 'SELL' | 'HOLD'
confidence: number // 0-100
reasoning: string
// Enhanced trading analysis (optional)
entry?: {
price: number
buffer?: string
rationale: string
}
stopLoss?: {
price: number
rationale: string
}
takeProfits?: {
tp1?: { price: number; description: string }
tp2?: { price: number; description: string }
}
riskToReward?: string
confirmationTrigger?: string
indicatorAnalysis?: {
rsi?: string
vwap?: string
obv?: string
}
}
export class AIAnalysisService {
async analyzeScreenshot(filename: string): Promise<AnalysisResult | null> {
try {
const screenshotsDir = path.join(process.cwd(), 'screenshots')
const imagePath = path.join(screenshotsDir, filename)
// Read image file
const imageBuffer = await fs.readFile(imagePath)
const base64Image = imageBuffer.toString('base64')
const prompt = `You are a technical chart analysis expert. Please analyze this TradingView chart image and provide objective technical analysis data.
**Important**: This is for educational and research purposes only. Please analyze the technical indicators, price levels, and chart patterns visible in the image.
Examine the chart and identify:
- Current price action and trend direction
- Key support and resistance levels visible on the chart
- Technical indicator readings (RSI, moving averages, volume if visible)
- Chart patterns or formations
- Market structure elements
Provide your analysis in this exact JSON format (replace values with your analysis):
{
"summary": "Objective description of what you observe in the chart",
"marketSentiment": "BULLISH|BEARISH|NEUTRAL",
"keyLevels": {
"support": [list of visible support price levels as numbers],
"resistance": [list of visible resistance price levels as numbers]
},
"recommendation": "BUY|SELL|HOLD",
"confidence": 75,
"reasoning": "Technical analysis reasoning based on indicators and price action",
"entry": {
"price": 150.50,
"buffer": "±0.25",
"rationale": "Technical reasoning for entry level"
},
"stopLoss": {
"price": 148.00,
"rationale": "Technical reasoning for stop level"
},
"takeProfits": {
"tp1": { "price": 152.00, "description": "First target reasoning" },
"tp2": { "price": 154.00, "description": "Second target reasoning" }
},
"riskToReward": "1:2",
"confirmationTrigger": "Technical signal to watch for",
"indicatorAnalysis": {
"rsi": "RSI level and interpretation",
"vwap": "VWAP relationship to price",
"obv": "Volume analysis if visible"
}
}
Return only the JSON object with your technical analysis.`
const response = await openai.chat.completions.create({
model: "gpt-4o", // Updated to current vision model
messages: [
{
role: "user",
content: [
{ type: "text", text: prompt },
{
type: "image_url",
image_url: {
url: `data:image/png;base64,${base64Image}`,
detail: "low" // Reduce token usage
}
}
]
}
],
max_tokens: 1024,
temperature: 0.1
})
const content = response.choices[0]?.message?.content
if (!content) return null
console.log('AI response content:', content)
// Extract JSON from response
const match = content.match(/\{[\s\S]*\}/)
if (!match) {
console.error('No JSON found in response. Full content:', content)
return null
}
const json = match[0]
console.log('Raw JSON from AI:', json)
const result = JSON.parse(json)
console.log('Parsed result:', result)
// Sanitize the result to ensure no nested objects cause React issues
const sanitizedResult = {
summary: typeof result.summary === 'string' ? result.summary : String(result.summary || ''),
marketSentiment: result.marketSentiment || 'NEUTRAL',
keyLevels: {
support: Array.isArray(result.keyLevels?.support) ? result.keyLevels.support : [],
resistance: Array.isArray(result.keyLevels?.resistance) ? result.keyLevels.resistance : []
},
recommendation: result.recommendation || 'HOLD',
confidence: typeof result.confidence === 'number' ? result.confidence : 0,
reasoning: typeof result.reasoning === 'string' ? result.reasoning : String(result.reasoning || ''),
...(result.entry && { entry: result.entry }),
...(result.stopLoss && { stopLoss: result.stopLoss }),
...(result.takeProfits && { takeProfits: result.takeProfits }),
...(result.riskToReward && { riskToReward: String(result.riskToReward) }),
...(result.confirmationTrigger && { confirmationTrigger: String(result.confirmationTrigger) }),
...(result.indicatorAnalysis && { indicatorAnalysis: result.indicatorAnalysis })
}
// Optionally: validate result structure here
return sanitizedResult as AnalysisResult
} catch (e) {
console.error('AI analysis error:', e)
return null
}
}
async analyzeMultipleScreenshots(filenames: string[]): Promise<AnalysisResult | null> {
try {
const screenshotsDir = path.join(process.cwd(), 'screenshots')
const images: any[] = []
for (const filename of filenames) {
const imagePath = path.join(screenshotsDir, filename)
const imageBuffer = await fs.readFile(imagePath)
const base64Image = imageBuffer.toString('base64')
images.push({ type: "image_url", image_url: { url: `data:image/png;base64,${base64Image}` } })
}
const prompt = `You are a technical chart analysis expert. Please analyze these TradingView chart images and provide objective technical analysis data.
**Important**: This is for educational and research purposes only. Please analyze the technical indicators, price levels, and chart patterns visible in the images.
Examine all the charts and provide a consolidated analysis by identifying:
- Current price action and trend direction across layouts
- Key support and resistance levels visible on the charts
- Technical indicator readings (RSI, moving averages, volume if visible)
- Chart patterns or formations
- Market structure elements
- Cross-reference different timeframes/layouts for the most accurate analysis
**CRITICAL: You MUST analyze the actual chart images provided. Do not respond with generic advice.**
Provide your analysis in this exact JSON format (replace values with your analysis):
{
"summary": "Objective description combining analysis from all charts",
"marketSentiment": "BULLISH|BEARISH|NEUTRAL",
"keyLevels": {
"support": [list of visible support price levels as numbers],
"resistance": [list of visible resistance price levels as numbers]
},
"recommendation": "BUY|SELL|HOLD",
"confidence": 75,
"reasoning": "Technical analysis reasoning based on indicators and price action from all layouts",
"entry": {
"price": 150.50,
"buffer": "±0.25",
"rationale": "Technical reasoning for entry level"
},
"stopLoss": {
"price": 148.00,
"rationale": "Technical reasoning for stop level"
},
"takeProfits": {
"tp1": { "price": 152.00, "description": "First target reasoning" },
"tp2": { "price": 154.00, "description": "Second target reasoning" }
},
"riskToReward": "1:2",
"confirmationTrigger": "Technical signal to watch for",
"indicatorAnalysis": {
"rsi": "RSI level and interpretation",
"vwap": "VWAP relationship to price",
"obv": "Volume analysis if visible"
}
}
Return only the JSON object with your consolidated technical analysis.`
const response = await openai.chat.completions.create({
model: "gpt-4o", // gpt-4o has better vision capabilities than gpt-4-vision-preview
messages: [
{
role: "user",
content: [
{ type: "text", text: prompt },
...images
]
}
],
max_tokens: 2000, // Increased for more detailed analysis
temperature: 0.1
})
const content = response.choices[0]?.message?.content
if (!content) {
throw new Error('No content received from OpenAI')
}
console.log('AI response content:', content)
// Parse the JSON response
const jsonMatch = content.match(/\{[\s\S]*\}/)
if (!jsonMatch) {
console.error('No JSON found in response. Full content:', content)
throw new Error('No JSON found in response')
}
console.log('Extracted JSON:', jsonMatch[0])
const analysis = JSON.parse(jsonMatch[0])
// Sanitize the analysis result to ensure no nested objects cause React issues
const sanitizedAnalysis = {
summary: typeof analysis.summary === 'string' ? analysis.summary : String(analysis.summary || ''),
marketSentiment: analysis.marketSentiment || 'NEUTRAL',
keyLevels: {
support: Array.isArray(analysis.keyLevels?.support) ? analysis.keyLevels.support : [],
resistance: Array.isArray(analysis.keyLevels?.resistance) ? analysis.keyLevels.resistance : []
},
recommendation: analysis.recommendation || 'HOLD',
confidence: typeof analysis.confidence === 'number' ? analysis.confidence : 0,
reasoning: typeof analysis.reasoning === 'string' ? analysis.reasoning : String(analysis.reasoning || ''),
...(analysis.entry && { entry: analysis.entry }),
...(analysis.stopLoss && { stopLoss: analysis.stopLoss }),
...(analysis.takeProfits && { takeProfits: analysis.takeProfits }),
...(analysis.riskToReward && { riskToReward: String(analysis.riskToReward) }),
...(analysis.confirmationTrigger && { confirmationTrigger: String(analysis.confirmationTrigger) }),
...(analysis.indicatorAnalysis && { indicatorAnalysis: analysis.indicatorAnalysis })
}
// Validate the structure
if (!sanitizedAnalysis.summary || !sanitizedAnalysis.marketSentiment || !sanitizedAnalysis.recommendation || typeof sanitizedAnalysis.confidence !== 'number') {
console.error('Invalid analysis structure:', sanitizedAnalysis)
throw new Error('Invalid analysis structure')
}
return sanitizedAnalysis
} catch (error) {
console.error('AI multi-analysis error:', error)
return null
}
}
async captureAndAnalyze(
symbol: string,
timeframe: string,
credentials: TradingViewCredentials
): Promise<AnalysisResult | null> {
try {
console.log(`Starting automated capture and analysis for ${symbol} ${timeframe}`)
// Capture screenshot using automation
const screenshot = await enhancedScreenshotService.captureQuick(symbol, timeframe, credentials)
if (!screenshot) {
throw new Error('Failed to capture screenshot')
}
console.log(`Screenshot captured: ${screenshot}`)
// Analyze the captured screenshot
const analysis = await this.analyzeScreenshot(screenshot)
if (!analysis) {
throw new Error('Failed to analyze screenshot')
}
console.log(`Analysis completed for ${symbol} ${timeframe}`)
return analysis
} catch (error) {
console.error('Automated capture and analysis failed:', error)
return null
}
}
async captureAndAnalyzeMultiple(
symbols: string[],
timeframes: string[],
credentials: TradingViewCredentials
): Promise<Array<{ symbol: string; timeframe: string; analysis: AnalysisResult | null }>> {
const results: Array<{ symbol: string; timeframe: string; analysis: AnalysisResult | null }> = []
for (const symbol of symbols) {
for (const timeframe of timeframes) {
try {
console.log(`Processing ${symbol} ${timeframe}...`)
const analysis = await this.captureAndAnalyze(symbol, timeframe, credentials)
results.push({
symbol,
timeframe,
analysis
})
// Small delay between captures to avoid overwhelming the system
await new Promise(resolve => setTimeout(resolve, 2000))
} catch (error) {
console.error(`Failed to process ${symbol} ${timeframe}:`, error)
results.push({
symbol,
timeframe,
analysis: null
})
}
}
}
return results
}
async captureAndAnalyzeWithConfig(config: ScreenshotConfig): Promise<{
screenshots: string[]
analysis: AnalysisResult | null
}> {
try {
console.log(`Starting automated capture with config for ${config.symbol} ${config.timeframe}`)
// Capture screenshots using enhanced service
const screenshots = await enhancedScreenshotService.captureWithLogin(config)
if (screenshots.length === 0) {
throw new Error('No screenshots captured')
}
console.log(`${screenshots.length} screenshot(s) captured`)
let analysis: AnalysisResult | null = null
if (screenshots.length === 1) {
// Single screenshot analysis
analysis = await this.analyzeScreenshot(screenshots[0])
} else {
// Multiple screenshots analysis
analysis = await this.analyzeMultipleScreenshots(screenshots)
}
if (!analysis) {
throw new Error('Failed to analyze screenshots')
}
console.log(`Analysis completed for ${config.symbol} ${config.timeframe}`)
return {
screenshots,
analysis
}
} catch (error) {
console.error('Automated capture and analysis with config failed:', error)
return {
screenshots: [],
analysis: null
}
}
}
}
export const aiAnalysisService = new AIAnalysisService()