Fix chart loading issues and remove sample position data

- Fixed TradingChart data generation to use unique daily timestamps
- Removed sample position data from trading page
- Added better error handling and logging to chart initialization
- Fixed time format issues that were preventing chart rendering
- Added test pages for debugging chart functionality
This commit is contained in:
mindesbunister
2025-07-16 12:54:48 +02:00
parent 1ee8aa9fe7
commit 4fe9c1342c
8 changed files with 459 additions and 22 deletions

85
app/api-test/page.tsx Normal file
View File

@@ -0,0 +1,85 @@
'use client'
import React, { useEffect, useRef, useState } from 'react'
export default function ChartAPITest() {
const chartContainerRef = useRef<HTMLDivElement>(null)
const [logs, setLogs] = useState<string[]>([])
const addLog = (message: string) => {
console.log(message)
setLogs(prev => [...prev, `${new Date().toLocaleTimeString()}: ${message}`])
}
useEffect(() => {
if (!chartContainerRef.current) return
const testLightweightCharts = async () => {
try {
addLog('Importing lightweight-charts...')
const LightweightCharts = await import('lightweight-charts')
addLog('Import successful')
// Log what's available in the import
addLog('Available exports: ' + Object.keys(LightweightCharts).join(', '))
const { createChart } = LightweightCharts
addLog('createChart function available: ' + (typeof createChart))
// Create chart
const chart = createChart(chartContainerRef.current!, {
width: 600,
height: 300,
})
addLog('Chart created')
// Log chart methods
const chartMethods = Object.getOwnPropertyNames(Object.getPrototypeOf(chart))
addLog('Chart methods: ' + chartMethods.join(', '))
// Try to find the correct method for adding series
if ('addCandlestickSeries' in chart) {
addLog('addCandlestickSeries method found!')
} else if ('addCandles' in chart) {
addLog('addCandles method found!')
} else if ('addSeries' in chart) {
addLog('addSeries method found!')
} else {
addLog('No obvious candlestick method found')
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
addLog(`Error: ${errorMessage}`)
console.error('Error:', error)
}
}
testLightweightCharts()
}, [])
return (
<div className="min-h-screen bg-gray-900 p-8">
<h1 className="text-white text-2xl mb-4">Lightweight Charts API Test</h1>
<div className="mb-4">
<div
ref={chartContainerRef}
className="bg-gray-800 border border-gray-600 rounded"
style={{ width: '600px', height: '300px' }}
/>
</div>
<div>
<h2 className="text-white text-lg mb-2">API Investigation Logs</h2>
<div className="bg-gray-800 p-4 rounded max-h-96 overflow-y-auto">
{logs.map((log, index) => (
<div key={index} className="text-gray-300 text-sm font-mono mb-1">
{log}
</div>
))}
</div>
</div>
</div>
)
}

111
app/chart-debug/page.tsx Normal file
View File

@@ -0,0 +1,111 @@
'use client'
import React, { useEffect, useRef, useState } from 'react'
export default function ChartDebug() {
const chartContainerRef = useRef<HTMLDivElement>(null)
const [logs, setLogs] = useState<string[]>([])
const [chartCreated, setChartCreated] = useState(false)
const addLog = (message: string) => {
console.log(message)
setLogs(prev => [...prev, `${new Date().toLocaleTimeString()}: ${message}`])
}
useEffect(() => {
if (!chartContainerRef.current) {
addLog('Chart container ref not available')
return
}
const initChart = async () => {
try {
addLog('Starting chart initialization...')
// Import lightweight-charts
const LightweightCharts = await import('lightweight-charts')
addLog('Lightweight charts imported successfully')
const { createChart, CandlestickSeries } = LightweightCharts
addLog('createChart and CandlestickSeries extracted')
// Create chart with minimal options
const chart = createChart(chartContainerRef.current!, {
width: 600,
height: 300,
})
addLog('Chart created successfully')
setChartCreated(true)
// Add candlestick series with the correct v5 API
const candlestickSeries = chart.addSeries(CandlestickSeries, {
upColor: '#26a69a',
downColor: '#ef5350',
borderDownColor: '#ef5350',
borderUpColor: '#26a69a',
wickDownColor: '#ef5350',
wickUpColor: '#26a69a',
})
addLog('Candlestick series added')
// Very simple test data
const testData = [
{ time: '2023-01-01', open: 100, high: 110, low: 95, close: 105 },
{ time: '2023-01-02', open: 105, high: 115, low: 100, close: 110 },
{ time: '2023-01-03', open: 110, high: 120, low: 105, close: 115 },
{ time: '2023-01-04', open: 115, high: 125, low: 110, close: 120 },
{ time: '2023-01-05', open: 120, high: 130, low: 115, close: 125 },
]
addLog(`Setting data with ${testData.length} points`)
candlestickSeries.setData(testData)
addLog('Data set successfully - chart should be visible now')
// Cleanup function
return () => {
addLog('Cleaning up chart')
chart.remove()
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
addLog(`Error: ${errorMessage}`)
console.error('Chart error:', error)
}
}
initChart()
}, [])
return (
<div className="min-h-screen bg-gray-900 p-8">
<h1 className="text-white text-2xl mb-4">Chart Debug Test</h1>
<div className="mb-4">
<h2 className="text-white text-lg mb-2">Status</h2>
<div className="text-gray-400">
Chart Created: {chartCreated ? '✅ Yes' : '❌ No'}
</div>
</div>
<div className="mb-4">
<h2 className="text-white text-lg mb-2">Chart Container</h2>
<div
ref={chartContainerRef}
className="bg-gray-800 border border-gray-600 rounded"
style={{ width: '600px', height: '300px' }}
/>
</div>
<div>
<h2 className="text-white text-lg mb-2">Debug Logs</h2>
<div className="bg-gray-800 p-4 rounded max-h-60 overflow-y-auto">
{logs.map((log, index) => (
<div key={index} className="text-gray-300 text-sm font-mono">
{log}
</div>
))}
</div>
</div>
</div>
)
}

View File

@@ -1,6 +1,6 @@
'use client' 'use client'
import React from 'react' import React from 'react'
import TradingChart from '../../components/TradingChart.tsx' import TradingChart from '../../components/TradingChart'
export default function SimpleChartTest() { export default function SimpleChartTest() {
return ( return (

View File

@@ -0,0 +1,78 @@
'use client'
import React, { useEffect, useRef, useState } from 'react'
export default function MinimalChartTest() {
const chartContainerRef = useRef<HTMLDivElement>(null)
const [status, setStatus] = useState('Starting...')
const [error, setError] = useState<string | null>(null)
useEffect(() => {
if (!chartContainerRef.current) {
setStatus('No container ref')
return
}
const initChart = async () => {
try {
setStatus('Loading lightweight-charts...')
console.log('Starting chart init...')
const LightweightCharts = await import('lightweight-charts')
console.log('Lightweight charts loaded:', LightweightCharts)
setStatus('Charts library loaded')
const { createChart, CandlestickSeries } = LightweightCharts
console.log('createChart:', typeof createChart)
console.log('CandlestickSeries:', CandlestickSeries)
setStatus('Creating chart...')
const chart = createChart(chartContainerRef.current!, {
width: 800,
height: 400,
})
console.log('Chart created:', chart)
setStatus('Chart created')
setStatus('Adding series...')
const series = chart.addSeries(CandlestickSeries, {})
console.log('Series created:', series)
setStatus('Series added')
setStatus('Adding data...')
const data = [
{ time: '2025-01-01', open: 100, high: 110, low: 90, close: 105 },
{ time: '2025-01-02', open: 105, high: 115, low: 95, close: 110 },
{ time: '2025-01-03', open: 110, high: 120, low: 100, close: 115 },
]
series.setData(data)
console.log('Data set')
setStatus('Chart ready!')
} catch (err) {
console.error('Chart init error:', err)
const errorMsg = err instanceof Error ? err.message : String(err)
setError(errorMsg)
setStatus(`Error: ${errorMsg}`)
}
}
initChart()
}, [])
return (
<div className="min-h-screen bg-gray-900 p-8">
<h1 className="text-white text-2xl mb-4">Minimal Chart Test</h1>
<div className="text-gray-300 mb-4">Status: {status}</div>
{error && (
<div className="text-red-400 mb-4 p-4 bg-red-900/20 rounded">
Error: {error}
</div>
)}
<div
ref={chartContainerRef}
className="bg-gray-800 border border-gray-600"
style={{ width: '800px', height: '400px' }}
/>
</div>
)
}

View File

@@ -1,30 +1,41 @@
'use client' 'use client'
import React, { useEffect, useRef } from 'react' import React, { useEffect, useRef, useState } from 'react'
export default function SimpleChart() { export default function SimpleChart() {
const chartContainerRef = useRef<HTMLDivElement>(null) const chartContainerRef = useRef<HTMLDivElement>(null)
const [status, setStatus] = useState('Initializing...')
useEffect(() => { useEffect(() => {
if (!chartContainerRef.current) return if (!chartContainerRef.current) return
const initChart = async () => { const initChart = async () => {
try { try {
setStatus('Loading lightweight-charts...')
console.log('Importing lightweight-charts...') console.log('Importing lightweight-charts...')
const LightweightCharts = await import('lightweight-charts')
console.log('Lightweight charts imported:', LightweightCharts)
const { createChart, ColorType } = LightweightCharts const LightweightCharts = await import('lightweight-charts')
console.log('Lightweight charts imported successfully')
setStatus('Creating chart...')
const { createChart, ColorType, CandlestickSeries } = LightweightCharts
const chart = createChart(chartContainerRef.current!, { const chart = createChart(chartContainerRef.current!, {
layout: { layout: {
background: { type: ColorType.Solid, color: '#1a1a1a' }, background: { type: ColorType.Solid, color: '#1a1a1a' },
textColor: '#ffffff', textColor: '#ffffff',
}, },
width: 800, width: chartContainerRef.current!.clientWidth || 800,
height: 400, height: 400,
grid: {
vertLines: { color: 'rgba(42, 46, 57, 0.5)' },
horzLines: { color: 'rgba(42, 46, 57, 0.5)' },
},
}) })
const candlestickSeries = chart.addCandlestickSeries({ setStatus('Adding candlestick series...')
console.log('Chart created, adding candlestick series...')
const candlestickSeries = chart.addSeries(CandlestickSeries, {
upColor: '#26a69a', upColor: '#26a69a',
downColor: '#ef5350', downColor: '#ef5350',
borderDownColor: '#ef5350', borderDownColor: '#ef5350',
@@ -33,19 +44,57 @@ export default function SimpleChart() {
wickUpColor: '#26a69a', wickUpColor: '#26a69a',
}) })
// Simple test data // Generate sample data
candlestickSeries.setData([ const data = []
{ time: '2023-12-22', open: 75.16, high: 82.84, low: 36.16, close: 45.72 }, const baseTime = new Date(Date.now() - 100 * 60 * 1000) // 100 minutes ago
{ time: '2023-12-23', open: 45.12, high: 53.90, low: 45.12, close: 48.09 }, let price = 166.5
{ time: '2023-12-24', open: 60.71, high: 60.71, low: 53.39, close: 59.29 },
{ time: '2023-12-25', open: 68.26, high: 68.26, low: 59.04, close: 60.50 },
{ time: '2023-12-26', open: 67.71, high: 105.85, low: 66.67, close: 91.04 },
])
for (let i = 0; i < 100; i++) {
const currentTime = new Date(baseTime.getTime() + i * 60 * 1000) // 1 minute intervals
const timeString = currentTime.toISOString().split('T')[0] // YYYY-MM-DD format
const change = (Math.random() - 0.5) * 2 // Random price change
const open = price
const close = price + change
const high = Math.max(open, close) + Math.random() * 1
const low = Math.min(open, close) - Math.random() * 1
data.push({
time: timeString,
open: Number(open.toFixed(2)),
high: Number(high.toFixed(2)),
low: Number(low.toFixed(2)),
close: Number(close.toFixed(2)),
})
price = close
}
console.log('Setting chart data...', data.length, 'points')
candlestickSeries.setData(data)
setStatus('Chart loaded successfully!')
console.log('Chart created successfully!') console.log('Chart created successfully!')
// Handle resize
const handleResize = () => {
if (chartContainerRef.current) {
chart.applyOptions({
width: chartContainerRef.current.clientWidth,
})
}
}
window.addEventListener('resize', handleResize)
return () => {
window.removeEventListener('resize', handleResize)
chart.remove()
}
} catch (error) { } catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
console.error('Error creating chart:', error) console.error('Error creating chart:', error)
setStatus(`Error: ${errorMessage}`)
} }
} }
@@ -55,7 +104,12 @@ export default function SimpleChart() {
return ( return (
<div className="min-h-screen bg-gray-900 p-8"> <div className="min-h-screen bg-gray-900 p-8">
<h1 className="text-white text-2xl mb-4">Lightweight Charts Test</h1> <h1 className="text-white text-2xl mb-4">Lightweight Charts Test</h1>
<div ref={chartContainerRef} className="bg-gray-800 rounded" /> <div className="text-gray-400 mb-4">Status: {status}</div>
<div
ref={chartContainerRef}
className="bg-gray-800 rounded w-full h-96"
style={{ minHeight: '400px' }}
/>
</div> </div>
) )
} }

View File

@@ -4,10 +4,27 @@ import TradeExecutionPanel from '../../components/TradeExecutionPanel.js'
import PositionsPanel from '../../components/PositionsPanel.js' import PositionsPanel from '../../components/PositionsPanel.js'
import PendingOrdersPanel from '../../components/PendingOrdersPanel.js' import PendingOrdersPanel from '../../components/PendingOrdersPanel.js'
import TradesHistoryPanel from '../../components/TradesHistoryPanel.js' import TradesHistoryPanel from '../../components/TradesHistoryPanel.js'
import TradingChart from '../../components/TradingChart'
export default function TradingPage() { export default function TradingPage() {
return ( return (
<div className="space-y-8"> <div className="space-y-8">
{/* Trading Chart - Full Width */}
<div className="bg-gray-900 rounded-lg p-6">
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-semibold text-white">SOL/USDC</h2>
<div className="flex items-center space-x-4 text-sm text-gray-400">
<span>1M</span>
<span>5M</span>
<span className="text-blue-400">15M</span>
<span>1H</span>
<span>4H</span>
<span>1D</span>
</div>
</div>
<TradingChart symbol="SOL/USDC" positions={[]} />
</div>
<div className="grid grid-cols-1 xl:grid-cols-2 gap-8"> <div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
<div className="space-y-6"> <div className="space-y-6">
<TradeExecutionPanel /> <TradeExecutionPanel />

View File

@@ -0,0 +1,77 @@
'use client'
import React, { useEffect, useRef } from 'react'
export default function WorkingChart() {
const chartContainerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (!chartContainerRef.current) return
const initChart = async () => {
try {
const { createChart, CandlestickSeries } = await import('lightweight-charts')
const chart = createChart(chartContainerRef.current!, {
width: 800,
height: 400,
layout: {
textColor: '#ffffff',
background: { color: '#1a1a1a' },
},
})
const candlestickSeries = chart.addSeries(CandlestickSeries, {
upColor: '#26a69a',
downColor: '#ef5350',
})
// Simple working data - last 30 days
const data = []
const today = new Date()
let price = 166.5
for (let i = 29; i >= 0; i--) {
const date = new Date(today)
date.setDate(date.getDate() - i)
const timeString = date.toISOString().split('T')[0]
const change = (Math.random() - 0.5) * 4
const open = price
const close = price + change
const high = Math.max(open, close) + Math.random() * 2
const low = Math.min(open, close) - Math.random() * 2
data.push({
time: timeString,
open: Number(open.toFixed(2)),
high: Number(high.toFixed(2)),
low: Number(low.toFixed(2)),
close: Number(close.toFixed(2)),
})
price = close
}
candlestickSeries.setData(data)
return () => {
chart.remove()
}
} catch (error) {
console.error('Chart error:', error)
}
}
initChart()
}, [])
return (
<div className="min-h-screen bg-gray-900 p-8">
<h1 className="text-white text-2xl mb-4">Working Chart Test</h1>
<div
ref={chartContainerRef}
className="bg-gray-800 border border-gray-600"
/>
</div>
)
}

View File

@@ -33,7 +33,7 @@ export default function TradingChart({ symbol = 'SOL/USDC', positions = [] }: Tr
try { try {
// Dynamic import to avoid SSR issues // Dynamic import to avoid SSR issues
const LightweightCharts = await import('lightweight-charts') const LightweightCharts = await import('lightweight-charts')
const { createChart, ColorType, CrosshairMode, LineStyle } = LightweightCharts const { createChart, ColorType, CrosshairMode, LineStyle, CandlestickSeries } = LightweightCharts
chart.current = createChart(chartContainerRef.current!, { chart.current = createChart(chartContainerRef.current!, {
layout: { layout: {
@@ -58,7 +58,7 @@ export default function TradingChart({ symbol = 'SOL/USDC', positions = [] }: Tr
}) })
// Create candlestick series // Create candlestick series
candlestickSeries.current = chart.current.addCandlestickSeries({ candlestickSeries.current = chart.current.addSeries(CandlestickSeries, {
upColor: '#26a69a', upColor: '#26a69a',
downColor: '#ef5350', downColor: '#ef5350',
borderDownColor: '#ef5350', borderDownColor: '#ef5350',
@@ -68,12 +68,21 @@ export default function TradingChart({ symbol = 'SOL/USDC', positions = [] }: Tr
}) })
// Generate sample data // Generate sample data
console.log('Generating sample data...')
const data = generateSampleData() const data = generateSampleData()
console.log('Sample data generated:', data.length, 'points')
console.log('First few data points:', data.slice(0, 3))
console.log('Setting chart data...')
candlestickSeries.current.setData(data) candlestickSeries.current.setData(data)
console.log('Chart data set successfully')
// Add position overlays // Add position overlays
console.log('Adding position overlays...')
addPositionOverlays(LineStyle) addPositionOverlays(LineStyle)
console.log('Position overlays added')
console.log('Chart initialization complete')
setIsLoading(false) setIsLoading(false)
// Handle resize // Handle resize
@@ -95,6 +104,10 @@ export default function TradingChart({ symbol = 'SOL/USDC', positions = [] }: Tr
} }
} catch (error) { } catch (error) {
console.error('Failed to initialize chart:', error) console.error('Failed to initialize chart:', error)
console.error('Error details:', {
message: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined
})
setIsLoading(false) setIsLoading(false)
} }
} }
@@ -155,10 +168,12 @@ export default function TradingChart({ symbol = 'SOL/USDC', positions = [] }: Tr
const data = [] const data = []
const basePrice = 166.5 const basePrice = 166.5
let currentPrice = basePrice let currentPrice = basePrice
const now = new Date() const baseDate = new Date()
for (let i = 100; i >= 0; i--) { for (let i = 0; i < 100; i++) {
const time = Math.floor((now.getTime() - i * 60000) / 1000) // 1 minute intervals // Generate data for the last 100 days, one point per day
const currentTime = new Date(baseDate.getTime() - (99 - i) * 24 * 60 * 60 * 1000)
const timeString = currentTime.toISOString().split('T')[0] // YYYY-MM-DD format
const volatility = 0.02 const volatility = 0.02
const change = (Math.random() - 0.5) * volatility * currentPrice const change = (Math.random() - 0.5) * volatility * currentPrice
@@ -168,7 +183,7 @@ export default function TradingChart({ symbol = 'SOL/USDC', positions = [] }: Tr
const low = Math.min(open, close) - Math.random() * 0.01 * currentPrice const low = Math.min(open, close) - Math.random() * 0.01 * currentPrice
data.push({ data.push({
time, time: timeString,
open: Number(open.toFixed(2)), open: Number(open.toFixed(2)),
high: Number(high.toFixed(2)), high: Number(high.toFixed(2)),
low: Number(low.toFixed(2)), low: Number(low.toFixed(2)),