From 4fe9c1342c34320ec337428c737ac49c6b80991b Mon Sep 17 00:00:00 2001 From: mindesbunister Date: Wed, 16 Jul 2025 12:54:48 +0200 Subject: [PATCH] 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 --- app/api-test/page.tsx | 85 +++++++++++++++++++++++++++ app/chart-debug/page.tsx | 111 ++++++++++++++++++++++++++++++++++++ app/chart-test/page.tsx | 2 +- app/minimal-chart/page.tsx | 78 +++++++++++++++++++++++++ app/simple-chart/page.tsx | 84 ++++++++++++++++++++++----- app/trading/page.js | 17 ++++++ app/working-chart/page.tsx | 77 +++++++++++++++++++++++++ components/TradingChart.tsx | 27 +++++++-- 8 files changed, 459 insertions(+), 22 deletions(-) create mode 100644 app/api-test/page.tsx create mode 100644 app/chart-debug/page.tsx create mode 100644 app/minimal-chart/page.tsx create mode 100644 app/working-chart/page.tsx diff --git a/app/api-test/page.tsx b/app/api-test/page.tsx new file mode 100644 index 0000000..6507028 --- /dev/null +++ b/app/api-test/page.tsx @@ -0,0 +1,85 @@ +'use client' +import React, { useEffect, useRef, useState } from 'react' + +export default function ChartAPITest() { + const chartContainerRef = useRef(null) + const [logs, setLogs] = useState([]) + + 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 ( +
+

Lightweight Charts API Test

+ +
+
+
+ +
+

API Investigation Logs

+
+ {logs.map((log, index) => ( +
+ {log} +
+ ))} +
+
+
+ ) +} diff --git a/app/chart-debug/page.tsx b/app/chart-debug/page.tsx new file mode 100644 index 0000000..3662457 --- /dev/null +++ b/app/chart-debug/page.tsx @@ -0,0 +1,111 @@ +'use client' +import React, { useEffect, useRef, useState } from 'react' + +export default function ChartDebug() { + const chartContainerRef = useRef(null) + const [logs, setLogs] = useState([]) + 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 ( +
+

Chart Debug Test

+ +
+

Status

+
+ Chart Created: {chartCreated ? '✅ Yes' : '❌ No'} +
+
+ +
+

Chart Container

+
+
+ +
+

Debug Logs

+
+ {logs.map((log, index) => ( +
+ {log} +
+ ))} +
+
+
+ ) +} diff --git a/app/chart-test/page.tsx b/app/chart-test/page.tsx index d310e2e..dbb1798 100644 --- a/app/chart-test/page.tsx +++ b/app/chart-test/page.tsx @@ -1,6 +1,6 @@ 'use client' import React from 'react' -import TradingChart from '../../components/TradingChart.tsx' +import TradingChart from '../../components/TradingChart' export default function SimpleChartTest() { return ( diff --git a/app/minimal-chart/page.tsx b/app/minimal-chart/page.tsx new file mode 100644 index 0000000..5e6dc45 --- /dev/null +++ b/app/minimal-chart/page.tsx @@ -0,0 +1,78 @@ +'use client' +import React, { useEffect, useRef, useState } from 'react' + +export default function MinimalChartTest() { + const chartContainerRef = useRef(null) + const [status, setStatus] = useState('Starting...') + const [error, setError] = useState(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 ( +
+

Minimal Chart Test

+
Status: {status}
+ {error && ( +
+ Error: {error} +
+ )} +
+
+ ) +} diff --git a/app/simple-chart/page.tsx b/app/simple-chart/page.tsx index ec02992..7990537 100644 --- a/app/simple-chart/page.tsx +++ b/app/simple-chart/page.tsx @@ -1,30 +1,41 @@ 'use client' -import React, { useEffect, useRef } from 'react' +import React, { useEffect, useRef, useState } from 'react' export default function SimpleChart() { const chartContainerRef = useRef(null) + const [status, setStatus] = useState('Initializing...') useEffect(() => { if (!chartContainerRef.current) return const initChart = async () => { try { + setStatus('Loading 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!, { layout: { background: { type: ColorType.Solid, color: '#1a1a1a' }, textColor: '#ffffff', }, - width: 800, + width: chartContainerRef.current!.clientWidth || 800, 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', downColor: '#ef5350', borderDownColor: '#ef5350', @@ -33,19 +44,57 @@ export default function SimpleChart() { wickUpColor: '#26a69a', }) - // Simple test data - candlestickSeries.setData([ - { time: '2023-12-22', open: 75.16, high: 82.84, low: 36.16, close: 45.72 }, - { time: '2023-12-23', open: 45.12, high: 53.90, low: 45.12, close: 48.09 }, - { 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 }, - ]) + // Generate sample data + const data = [] + const baseTime = new Date(Date.now() - 100 * 60 * 1000) // 100 minutes ago + let price = 166.5 + 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!') + // 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) { + const errorMessage = error instanceof Error ? error.message : String(error) console.error('Error creating chart:', error) + setStatus(`Error: ${errorMessage}`) } } @@ -55,7 +104,12 @@ export default function SimpleChart() { return (

Lightweight Charts Test

-
+
Status: {status}
+
) } diff --git a/app/trading/page.js b/app/trading/page.js index ebebd11..db0a36c 100644 --- a/app/trading/page.js +++ b/app/trading/page.js @@ -4,10 +4,27 @@ import TradeExecutionPanel from '../../components/TradeExecutionPanel.js' import PositionsPanel from '../../components/PositionsPanel.js' import PendingOrdersPanel from '../../components/PendingOrdersPanel.js' import TradesHistoryPanel from '../../components/TradesHistoryPanel.js' +import TradingChart from '../../components/TradingChart' export default function TradingPage() { return (
+ {/* Trading Chart - Full Width */} +
+
+

SOL/USDC

+
+ 1M + 5M + 15M + 1H + 4H + 1D +
+
+ +
+
diff --git a/app/working-chart/page.tsx b/app/working-chart/page.tsx new file mode 100644 index 0000000..fbcc225 --- /dev/null +++ b/app/working-chart/page.tsx @@ -0,0 +1,77 @@ +'use client' +import React, { useEffect, useRef } from 'react' + +export default function WorkingChart() { + const chartContainerRef = useRef(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 ( +
+

Working Chart Test

+
+
+ ) +} diff --git a/components/TradingChart.tsx b/components/TradingChart.tsx index feebb68..492a2e8 100644 --- a/components/TradingChart.tsx +++ b/components/TradingChart.tsx @@ -33,7 +33,7 @@ export default function TradingChart({ symbol = 'SOL/USDC', positions = [] }: Tr try { // Dynamic import to avoid SSR issues const LightweightCharts = await import('lightweight-charts') - const { createChart, ColorType, CrosshairMode, LineStyle } = LightweightCharts + const { createChart, ColorType, CrosshairMode, LineStyle, CandlestickSeries } = LightweightCharts chart.current = createChart(chartContainerRef.current!, { layout: { @@ -58,7 +58,7 @@ export default function TradingChart({ symbol = 'SOL/USDC', positions = [] }: Tr }) // Create candlestick series - candlestickSeries.current = chart.current.addCandlestickSeries({ + candlestickSeries.current = chart.current.addSeries(CandlestickSeries, { upColor: '#26a69a', downColor: '#ef5350', borderDownColor: '#ef5350', @@ -68,12 +68,21 @@ export default function TradingChart({ symbol = 'SOL/USDC', positions = [] }: Tr }) // Generate sample data + console.log('Generating sample data...') 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) + console.log('Chart data set successfully') // Add position overlays + console.log('Adding position overlays...') addPositionOverlays(LineStyle) + console.log('Position overlays added') + console.log('Chart initialization complete') setIsLoading(false) // Handle resize @@ -95,6 +104,10 @@ export default function TradingChart({ symbol = 'SOL/USDC', positions = [] }: Tr } } catch (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) } } @@ -155,10 +168,12 @@ export default function TradingChart({ symbol = 'SOL/USDC', positions = [] }: Tr const data = [] const basePrice = 166.5 let currentPrice = basePrice - const now = new Date() + const baseDate = new Date() - for (let i = 100; i >= 0; i--) { - const time = Math.floor((now.getTime() - i * 60000) / 1000) // 1 minute intervals + for (let i = 0; i < 100; i++) { + // 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 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 data.push({ - time, + time: timeString, open: Number(open.toFixed(2)), high: Number(high.toFixed(2)), low: Number(low.toFixed(2)),