🔧 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
This commit is contained in:
mindesbunister
2025-07-12 15:08:24 +02:00
parent a8fcb33ec8
commit 483d4c6576
6 changed files with 363 additions and 116 deletions

View File

@@ -50,73 +50,53 @@ export class AIAnalysisService {
const imageBuffer = await fs.readFile(imagePath)
const base64Image = imageBuffer.toString('base64')
const prompt = `You are now a professional trading assistant focused on short-term crypto trading using 515min timeframes. You behave with the precision and decisiveness of a top proprietary desk trader. No vagueness, no fluff.
const prompt = `You are a technical chart analysis expert. Please analyze this TradingView chart image and provide objective technical analysis data.
Analyze the attached TradingView chart screenshot and provide a detailed trading analysis.
**Important**: This is for educational and research purposes only. Please analyze the technical indicators, price levels, and chart patterns visible in the image.
### WHEN GIVING A TRADE SETUP:
Be 100% SPECIFIC. Provide:
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
1. **ENTRY**
- Exact price level (with a ± entry buffer if needed)
- Rationale: e.g., "Rejection from 15 EMA + VWAP confluence near intraday supply"
Provide your analysis in this exact JSON format (replace values with your analysis):
2. **STOP-LOSS (SL)**
- Exact level (not arbitrary)
- Explain *why* it's there: "Above VWAP + failed breakout zone"
3. **TAKE PROFITS**
- TP1: Immediate structure (ex: previous low at $149.20)
- TP2: Extended target if momentum continues (e.g., $148.00)
- Mention **expected RSI/OBV behavior** at each TP zone
4. **RISK-TO-REWARD**
- Show R:R. Ex: "1:2.5 — Risking $X to potentially gain $Y"
5. **CONFIRMATION TRIGGER**
- Exact signal to wait for: e.g., "Bearish engulfing candle on rejection from VWAP zone"
- OBV: "Must be making lower highs + dropping below 30min average"
- RSI: "Should remain under 50 on rejection. Overbought ≥70 = wait"
6. **INDICATOR ANALYSIS**
- **RSI**: If RSI crosses above 70 while price is under resistance → *wait*
- **VWAP**: If price retakes VWAP with bullish momentum → *consider invalidation*
- **OBV**: If OBV starts climbing while price stays flat → *early exit or reconsider bias*
Return your answer as a JSON object with the following structure:
{
"summary": "Brief market summary",
"marketSentiment": "BULLISH" | "BEARISH" | "NEUTRAL",
"summary": "Objective description of what you observe in the chart",
"marketSentiment": "BULLISH|BEARISH|NEUTRAL",
"keyLevels": {
"support": [number array],
"resistance": [number array]
"support": [list of visible support price levels as numbers],
"resistance": [list of visible resistance price levels as numbers]
},
"recommendation": "BUY" | "SELL" | "HOLD",
"confidence": number (0-100),
"reasoning": "Detailed reasoning with specific levels, indicators, and confirmation triggers",
"recommendation": "BUY|SELL|HOLD",
"confidence": 75,
"reasoning": "Technical analysis reasoning based on indicators and price action",
"entry": {
"price": number,
"buffer": "string describing entry buffer",
"rationale": "string explaining entry logic"
"price": 150.50,
"buffer": "±0.25",
"rationale": "Technical reasoning for entry level"
},
"stopLoss": {
"price": number,
"rationale": "string explaining stop loss placement"
"price": 148.00,
"rationale": "Technical reasoning for stop level"
},
"takeProfits": {
"tp1": { "price": number, "description": "string" },
"tp2": { "price": number, "description": "string" }
"tp1": { "price": 152.00, "description": "First target reasoning" },
"tp2": { "price": 154.00, "description": "Second target reasoning" }
},
"riskToReward": "string like '1:2.5 - Risking $X to gain $Y'",
"confirmationTrigger": "string describing exact signal to wait for",
"riskToReward": "1:2",
"confirmationTrigger": "Technical signal to watch for",
"indicatorAnalysis": {
"rsi": "string describing RSI behavior",
"vwap": "string describing VWAP behavior",
"obv": "string describing OBV behavior"
"rsi": "RSI level and interpretation",
"vwap": "VWAP relationship to price",
"obv": "Volume analysis if visible"
}
}
Be concise but thorough. Only return valid JSON.`
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: [
@@ -124,17 +104,31 @@ Be concise but thorough. Only return valid JSON.`
role: "user",
content: [
{ type: "text", text: prompt },
{ type: "image_url", image_url: { url: `data:image/png;base64,${base64Image}` } }
{
type: "image_url",
image_url: {
url: `data:image/png;base64,${base64Image}`,
detail: "low" // Reduce token usage
}
}
]
}
],
max_tokens: 1024
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) return null
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)
@@ -181,83 +175,55 @@ Be concise but thorough. Only return valid JSON.`
images.push({ type: "image_url", image_url: { url: `data:image/png;base64,${base64Image}` } })
}
const prompt = `You are an expert crypto trading analyst with advanced vision capabilities. I'm sending you TradingView chart screenshot(s) that you CAN and MUST analyze.
const prompt = `You are a technical chart analysis expert. Please analyze these TradingView chart images and provide objective technical analysis data.
**IMPORTANT: You have full image analysis capabilities. Please analyze the TradingView chart images I'm providing.**
**Important**: This is for educational and research purposes only. Please analyze the technical indicators, price levels, and chart patterns visible in the images.
Analyze the attached TradingView chart screenshots (multiple layouts of the same symbol) and provide a comprehensive trading analysis by combining insights from all charts.
### TRADING ANALYSIS REQUIREMENTS:
You are a professional trading assistant focused on short-term crypto trading using 515min timeframes. You behave with the precision and decisiveness of a top proprietary desk trader. No vagueness, no fluff.
### WHEN GIVING A TRADE SETUP:
Be 100% SPECIFIC. Provide:
1. **ENTRY**
- Exact price level (with a ± entry buffer if needed)
- Rationale: e.g., "Rejection from 15 EMA + VWAP confluence near intraday supply"
2. **STOP-LOSS (SL)**
- Exact level (not arbitrary)
- Explain *why* it's there: "Above VWAP + failed breakout zone"
3. **TAKE PROFITS**
- TP1: Immediate structure (ex: previous low at $149.20)
- TP2: Extended target if momentum continues (e.g., $148.00)
- Mention **expected RSI/OBV behavior** at each TP zone
4. **RISK-TO-REWARD**
- Show R:R. Ex: "1:2.5 — Risking $X to potentially gain $Y"
5. **CONFIRMATION TRIGGER**
- Exact signal to wait for: e.g., "Bearish engulfing candle on rejection from VWAP zone"
- OBV: "Must be making lower highs + dropping below 30min average"
- RSI: "Should remain under 50 on rejection. Overbought ≥70 = wait"
6. **INDICATOR ANALYSIS**
- **RSI**: If RSI crosses above 70 while price is under resistance → *wait*
- **VWAP**: If price retakes VWAP with bullish momentum → *consider invalidation*
- **OBV**: If OBV starts climbing while price stays flat → *early exit or reconsider bias*
Cross-reference all layouts to provide the most accurate analysis. If layouts show conflicting signals, explain which one takes priority and why.
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.**
Return your answer as a JSON object with the following structure:
Provide your analysis in this exact JSON format (replace values with your analysis):
{
"summary": "Brief market summary combining all layouts",
"marketSentiment": "BULLISH" | "BEARISH" | "NEUTRAL",
"summary": "Objective description combining analysis from all charts",
"marketSentiment": "BULLISH|BEARISH|NEUTRAL",
"keyLevels": {
"support": [number array],
"resistance": [number array]
"support": [list of visible support price levels as numbers],
"resistance": [list of visible resistance price levels as numbers]
},
"recommendation": "BUY" | "SELL" | "HOLD",
"confidence": number (0-100),
"reasoning": "Detailed reasoning with specific levels, indicators, and confirmation triggers from all layouts",
"recommendation": "BUY|SELL|HOLD",
"confidence": 75,
"reasoning": "Technical analysis reasoning based on indicators and price action from all layouts",
"entry": {
"price": number,
"buffer": "string describing entry buffer",
"rationale": "string explaining entry logic"
"price": 150.50,
"buffer": "±0.25",
"rationale": "Technical reasoning for entry level"
},
"stopLoss": {
"price": number,
"rationale": "string explaining stop loss placement"
"price": 148.00,
"rationale": "Technical reasoning for stop level"
},
"takeProfits": {
"tp1": { "price": number, "description": "string" },
"tp2": { "price": number, "description": "string" }
"tp1": { "price": 152.00, "description": "First target reasoning" },
"tp2": { "price": 154.00, "description": "Second target reasoning" }
},
"riskToReward": "string like '1:2.5 - Risking $X to gain $Y'",
"confirmationTrigger": "string describing exact signal to wait for",
"riskToReward": "1:2",
"confirmationTrigger": "Technical signal to watch for",
"indicatorAnalysis": {
"rsi": "string describing RSI behavior",
"vwap": "string describing VWAP behavior",
"obv": "string describing OBV behavior"
"rsi": "RSI level and interpretation",
"vwap": "VWAP relationship to price",
"obv": "Volume analysis if visible"
}
}
Be concise but thorough. Only return valid JSON.`
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