Improve TradingView layout loading with better debugging and selection logic
- Added comprehensive layout menu item detection with multiple selectors - Implemented debug screenshots for layout menu and after layout changes - Added better error handling and logging for layout selection - Improved text matching with exact and partial match strategies - Added fallback comprehensive search with direct click functionality - Fixed TypeScript issues with element handle clicking
This commit is contained in:
@@ -40,6 +40,7 @@ export async function POST(req: NextRequest) {
|
|||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
...result,
|
...result,
|
||||||
|
layoutsAnalyzed: finalLayouts,
|
||||||
settings: {
|
settings: {
|
||||||
symbol: finalSymbol,
|
symbol: finalSymbol,
|
||||||
timeframe: finalTimeframe,
|
timeframe: finalTimeframe,
|
||||||
|
|||||||
@@ -15,21 +15,36 @@ const timeframes = [
|
|||||||
|
|
||||||
export default function AIAnalysisPanel() {
|
export default function AIAnalysisPanel() {
|
||||||
const [symbol, setSymbol] = useState('BTCUSD')
|
const [symbol, setSymbol] = useState('BTCUSD')
|
||||||
const [layout, setLayout] = useState(layouts[0])
|
const [selectedLayouts, setSelectedLayouts] = useState<string[]>([layouts[0]])
|
||||||
const [timeframe, setTimeframe] = useState('60')
|
const [timeframe, setTimeframe] = useState('60')
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
const [result, setResult] = useState<any>(null)
|
const [result, setResult] = useState<any>(null)
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const toggleLayout = (layout: string) => {
|
||||||
|
setSelectedLayouts(prev =>
|
||||||
|
prev.includes(layout)
|
||||||
|
? prev.filter(l => l !== layout)
|
||||||
|
: [...prev, layout]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
async function handleAnalyze() {
|
async function handleAnalyze() {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
setError(null)
|
setError(null)
|
||||||
setResult(null)
|
setResult(null)
|
||||||
|
|
||||||
|
if (selectedLayouts.length === 0) {
|
||||||
|
setError('Please select at least one layout')
|
||||||
|
setLoading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/analyze', {
|
const res = await fetch('/api/analyze', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ symbol, layout, timeframe })
|
body: JSON.stringify({ symbol, layouts: selectedLayouts, timeframe })
|
||||||
})
|
})
|
||||||
const data = await res.json()
|
const data = await res.json()
|
||||||
if (!res.ok) throw new Error(data.error || 'Unknown error')
|
if (!res.ok) throw new Error(data.error || 'Unknown error')
|
||||||
@@ -50,13 +65,6 @@ export default function AIAnalysisPanel() {
|
|||||||
onChange={e => setSymbol(e.target.value)}
|
onChange={e => setSymbol(e.target.value)}
|
||||||
placeholder="Symbol (e.g. BTCUSD)"
|
placeholder="Symbol (e.g. BTCUSD)"
|
||||||
/>
|
/>
|
||||||
<select
|
|
||||||
className="input input-bordered"
|
|
||||||
value={layout}
|
|
||||||
onChange={e => setLayout(e.target.value)}
|
|
||||||
>
|
|
||||||
{layouts.map(l => <option key={l} value={l}>{l}</option>)}
|
|
||||||
</select>
|
|
||||||
<select
|
<select
|
||||||
className="input input-bordered"
|
className="input input-bordered"
|
||||||
value={timeframe}
|
value={timeframe}
|
||||||
@@ -68,6 +76,31 @@ export default function AIAnalysisPanel() {
|
|||||||
{loading ? 'Analyzing...' : 'Analyze'}
|
{loading ? 'Analyzing...' : 'Analyze'}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Layout selection */}
|
||||||
|
<div className="mb-4">
|
||||||
|
<label className="block text-sm font-medium text-gray-300 mb-2">
|
||||||
|
Select Layouts for Analysis:
|
||||||
|
</label>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{layouts.map(layout => (
|
||||||
|
<label key={layout} className="flex items-center gap-2 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={selectedLayouts.includes(layout)}
|
||||||
|
onChange={() => toggleLayout(layout)}
|
||||||
|
className="form-checkbox h-4 w-4 text-blue-600 rounded"
|
||||||
|
/>
|
||||||
|
<span className="text-sm text-gray-300">{layout}</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{selectedLayouts.length > 0 && (
|
||||||
|
<div className="text-xs text-gray-400 mt-1">
|
||||||
|
Selected: {selectedLayouts.join(', ')}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
{error && (
|
{error && (
|
||||||
<div className="text-red-400 mb-2">
|
<div className="text-red-400 mb-2">
|
||||||
{error.includes('frame was detached') ? (
|
{error.includes('frame was detached') ? (
|
||||||
@@ -93,12 +126,19 @@ export default function AIAnalysisPanel() {
|
|||||||
)}
|
)}
|
||||||
{result && (
|
{result && (
|
||||||
<div className="bg-gray-800 rounded p-4 mt-4">
|
<div className="bg-gray-800 rounded p-4 mt-4">
|
||||||
<div><b>Summary:</b> {result.summary}</div>
|
{result.layoutsAnalyzed && (
|
||||||
<div><b>Sentiment:</b> {result.marketSentiment}</div>
|
<div className="mb-3 text-sm text-gray-400">
|
||||||
<div><b>Recommendation:</b> {result.recommendation} ({result.confidence}%)</div>
|
<b>Layouts analyzed:</b> {result.layoutsAnalyzed.join(', ')}
|
||||||
<div><b>Support:</b> {result.keyLevels?.support?.join(', ')}</div>
|
</div>
|
||||||
<div><b>Resistance:</b> {result.keyLevels?.resistance?.join(', ')}</div>
|
)}
|
||||||
<div><b>Reasoning:</b> {result.reasoning}</div>
|
<div className="space-y-2">
|
||||||
|
<div><b>Summary:</b> {result.summary}</div>
|
||||||
|
<div><b>Sentiment:</b> {result.marketSentiment}</div>
|
||||||
|
<div><b>Recommendation:</b> {result.recommendation} ({result.confidence}%)</div>
|
||||||
|
<div><b>Support:</b> {result.keyLevels?.support?.join(', ')}</div>
|
||||||
|
<div><b>Resistance:</b> {result.keyLevels?.resistance?.join(', ')}</div>
|
||||||
|
<div><b>Reasoning:</b> {result.reasoning}</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -306,50 +306,72 @@ export class TradingViewCapture {
|
|||||||
if (layoutButton) {
|
if (layoutButton) {
|
||||||
await layoutButton.click()
|
await layoutButton.click()
|
||||||
console.log('Clicked layout button')
|
console.log('Clicked layout button')
|
||||||
await new Promise(res => setTimeout(res, 1000))
|
|
||||||
|
|
||||||
// Look for search input or layout items
|
// Wait longer for the layout menu to appear
|
||||||
const searchSelectors = [
|
await new Promise(res => setTimeout(res, 2000))
|
||||||
'input[name="search"]',
|
|
||||||
'input[placeholder*="search" i]',
|
// Take a debug screenshot of the layout menu
|
||||||
'input[type="search"]',
|
const debugMenuPath = path.resolve(`debug_layout_menu_${layout.replace(/\s+/g, '_')}.png`) as `${string}.png`
|
||||||
'input[data-name="search"]'
|
await page.screenshot({ path: debugMenuPath })
|
||||||
|
console.log('Layout menu screenshot saved:', debugMenuPath)
|
||||||
|
|
||||||
|
// Look for layout menu items with more specific selectors
|
||||||
|
const layoutItemSelectors = [
|
||||||
|
`[data-name="chart-layout-list-item"]`,
|
||||||
|
`[data-testid*="layout"]`,
|
||||||
|
`.layout-item`,
|
||||||
|
`[role="option"]`,
|
||||||
|
`[role="menuitem"]`,
|
||||||
|
`.tv-dropdown-behavior__item`,
|
||||||
|
`.tv-menu__item`,
|
||||||
|
`li[data-value*="${layout}"]`,
|
||||||
|
`div[data-layout-name="${layout}"]`
|
||||||
]
|
]
|
||||||
|
|
||||||
let searchInput = null
|
let layoutItem = null
|
||||||
for (const selector of searchSelectors) {
|
let foundMethod = ''
|
||||||
|
let foundElement = false
|
||||||
|
|
||||||
|
// Try to find layout item by exact text match first
|
||||||
|
for (const selector of layoutItemSelectors) {
|
||||||
try {
|
try {
|
||||||
searchInput = await page.waitForSelector(selector, { timeout: 3000 })
|
console.log(`Trying selector: ${selector}`)
|
||||||
if (searchInput) break
|
const items = await page.$$(selector)
|
||||||
|
console.log(`Found ${items.length} items with selector: ${selector}`)
|
||||||
|
|
||||||
|
for (const item of items) {
|
||||||
|
const text = await page.evaluate(el => {
|
||||||
|
const element = el as HTMLElement
|
||||||
|
return (element.innerText || element.textContent || '').trim()
|
||||||
|
}, item)
|
||||||
|
console.log(`Item text: "${text}"`)
|
||||||
|
|
||||||
|
if (text && text.toLowerCase() === layout.toLowerCase()) {
|
||||||
|
layoutItem = item
|
||||||
|
foundMethod = `exact match with selector: ${selector}`
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (layoutItem) break
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// Continue to next selector
|
console.log(`Error with selector ${selector}:`, e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (searchInput) {
|
// If no exact match, try partial match
|
||||||
console.log('Found search input, typing layout name...')
|
if (!layoutItem) {
|
||||||
await searchInput.type(layout, { delay: 50 })
|
|
||||||
await new Promise(res => setTimeout(res, 2000))
|
|
||||||
|
|
||||||
// Try to find and click the layout item
|
|
||||||
const layoutItemSelectors = [
|
|
||||||
'[data-name="chart-layout-list-item"]',
|
|
||||||
'[data-testid*="layout-item"]',
|
|
||||||
'.layout-item',
|
|
||||||
'[role="option"]'
|
|
||||||
]
|
|
||||||
|
|
||||||
let layoutItem = null
|
|
||||||
for (const selector of layoutItemSelectors) {
|
for (const selector of layoutItemSelectors) {
|
||||||
try {
|
try {
|
||||||
const items = await page.$$(selector)
|
const items = await page.$$(selector)
|
||||||
for (const item of items) {
|
for (const item of items) {
|
||||||
const text = await page.evaluate(el => {
|
const text = await page.evaluate(el => {
|
||||||
const element = el as HTMLElement
|
const element = el as HTMLElement
|
||||||
return element.innerText || element.textContent
|
return (element.innerText || element.textContent || '').trim()
|
||||||
}, item)
|
}, item)
|
||||||
|
|
||||||
if (text && text.toLowerCase().includes(layout.toLowerCase())) {
|
if (text && text.toLowerCase().includes(layout.toLowerCase())) {
|
||||||
layoutItem = item
|
layoutItem = item
|
||||||
|
foundMethod = `partial match with selector: ${selector}`
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -358,33 +380,104 @@ export class TradingViewCapture {
|
|||||||
// Continue to next selector
|
// Continue to next selector
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (layoutItem) {
|
|
||||||
await layoutItem.click()
|
|
||||||
console.log('Clicked layout item:', layout)
|
|
||||||
} else {
|
|
||||||
console.log('Layout item not found, trying generic approach...')
|
|
||||||
await page.evaluate((layout) => {
|
|
||||||
const items = Array.from(document.querySelectorAll('*'))
|
|
||||||
const item = items.find(el => el.textContent?.toLowerCase().includes(layout.toLowerCase()))
|
|
||||||
if (item) (item as HTMLElement).click()
|
|
||||||
}, layout)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
console.log('Search input not found, trying to find layout directly...')
|
|
||||||
await page.evaluate((layout) => {
|
|
||||||
const items = Array.from(document.querySelectorAll('*'))
|
|
||||||
const item = items.find(el => el.textContent?.toLowerCase().includes(layout.toLowerCase()))
|
|
||||||
if (item) (item as HTMLElement).click()
|
|
||||||
}, layout)
|
|
||||||
}
|
}
|
||||||
await new Promise(res => setTimeout(res, 4000))
|
|
||||||
console.log('Layout loaded:', layout)
|
// If still no match, try a more comprehensive search
|
||||||
|
if (!layoutItem) {
|
||||||
|
console.log('No layout item found with standard selectors, trying comprehensive search...')
|
||||||
|
const foundElement = await page.evaluate((layout) => {
|
||||||
|
const allElements = Array.from(document.querySelectorAll('*'))
|
||||||
|
|
||||||
|
// Look for elements that contain the layout name
|
||||||
|
const candidates = allElements.filter(el => {
|
||||||
|
const text = (el.textContent || '').trim()
|
||||||
|
return text && text.toLowerCase().includes(layout.toLowerCase())
|
||||||
|
})
|
||||||
|
|
||||||
|
console.log('Found candidates:', candidates.map(el => ({
|
||||||
|
tag: el.tagName,
|
||||||
|
text: el.textContent?.trim(),
|
||||||
|
classes: el.className
|
||||||
|
})))
|
||||||
|
|
||||||
|
// Prioritize clickable elements
|
||||||
|
const clickable = candidates.find(el =>
|
||||||
|
el.tagName === 'BUTTON' ||
|
||||||
|
el.tagName === 'A' ||
|
||||||
|
el.hasAttribute('role') ||
|
||||||
|
el.classList.contains('item') ||
|
||||||
|
el.classList.contains('option') ||
|
||||||
|
el.classList.contains('menu')
|
||||||
|
)
|
||||||
|
|
||||||
|
if (clickable) {
|
||||||
|
(clickable as HTMLElement).click()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fall back to exact text match
|
||||||
|
const exactMatch = candidates.find(el =>
|
||||||
|
(el.textContent || '').trim().toLowerCase() === layout.toLowerCase()
|
||||||
|
)
|
||||||
|
|
||||||
|
if (exactMatch) {
|
||||||
|
(exactMatch as HTMLElement).click()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}, layout)
|
||||||
|
|
||||||
|
if (foundElement) {
|
||||||
|
foundMethod = 'comprehensive search with click'
|
||||||
|
console.log(`Found and clicked layout item "${layout}" using: ${foundMethod}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (layoutItem) {
|
||||||
|
console.log(`Found layout item "${layout}" using: ${foundMethod}`)
|
||||||
|
await layoutItem.click()
|
||||||
|
console.log('Clicked layout item:', layout)
|
||||||
|
|
||||||
|
// Wait for layout to actually load
|
||||||
|
await new Promise(res => setTimeout(res, 5000))
|
||||||
|
|
||||||
|
// Take a screenshot after layout change
|
||||||
|
const debugAfterPath = path.resolve(`debug_after_layout_${layout.replace(/\s+/g, '_')}.png`) as `${string}.png`
|
||||||
|
await page.screenshot({ path: debugAfterPath })
|
||||||
|
console.log('After layout change screenshot saved:', debugAfterPath)
|
||||||
|
|
||||||
|
} else if (foundElement && foundMethod === 'comprehensive search with click') {
|
||||||
|
console.log('Layout item was clicked via comprehensive search')
|
||||||
|
|
||||||
|
// Wait for layout to actually load
|
||||||
|
await new Promise(res => setTimeout(res, 5000))
|
||||||
|
|
||||||
|
// Take a screenshot after layout change
|
||||||
|
const debugAfterPath = path.resolve(`debug_after_layout_${layout.replace(/\s+/g, '_')}.png`) as `${string}.png`
|
||||||
|
await page.screenshot({ path: debugAfterPath })
|
||||||
|
console.log('After layout change screenshot saved:', debugAfterPath)
|
||||||
|
|
||||||
|
} else {
|
||||||
|
console.log('Layout item not found with any method')
|
||||||
|
|
||||||
|
// List all text content on the page for debugging
|
||||||
|
const allTexts = await page.evaluate(() => {
|
||||||
|
const elements = Array.from(document.querySelectorAll('*'))
|
||||||
|
return elements
|
||||||
|
.map(el => (el.textContent || '').trim())
|
||||||
|
.filter(text => text && text.length > 0 && text.length < 100)
|
||||||
|
.slice(0, 50) // Limit to first 50 for debugging
|
||||||
|
})
|
||||||
|
console.log('Available texts on page:', allTexts)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
console.log('Layout button not found, skipping layout loading')
|
console.log('Layout button not found, skipping layout loading')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log('Layout loading completed for:', layout)
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
const debugLayoutErrorPath = path.resolve('debug_layout_error.png') as `${string}.png`
|
const debugLayoutErrorPath = path.resolve(`debug_layout_error_${layout.replace(/\s+/g, '_')}.png`) as `${string}.png`
|
||||||
await page.screenshot({ path: debugLayoutErrorPath })
|
await page.screenshot({ path: debugLayoutErrorPath })
|
||||||
console.error('TradingView layout not found or could not be loaded:', e)
|
console.error('TradingView layout not found or could not be loaded:', e)
|
||||||
console.log('Continuing without layout...')
|
console.log('Continuing without layout...')
|
||||||
|
|||||||
BIN
screenshots/SOLUSD_5_1752064560978_Diy module.png
Normal file
BIN
screenshots/SOLUSD_5_1752064560978_Diy module.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 207 KiB |
BIN
screenshots/SOLUSD_5_1752064560978_ai.png
Normal file
BIN
screenshots/SOLUSD_5_1752064560978_ai.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 207 KiB |
9
trading-settings.json
Normal file
9
trading-settings.json
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"symbol": "SOLUSD",
|
||||||
|
"timeframe": "5",
|
||||||
|
"layouts": [
|
||||||
|
"ai",
|
||||||
|
"Diy module"
|
||||||
|
],
|
||||||
|
"lastUpdated": 1752064560981
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user