@@ -13,7 +13,7 @@ import {
1313 PERIOD_BUTTONS ,
1414 PERIOD_CONFIG ,
1515} from '@/lib/constants' ;
16- import { convertOHLCData , convertOHLCToCandlestickData } from '@/lib/utils' ;
16+ import { convertOHLCData } from '@/lib/utils' ;
1717const { getCoinOHLC } = await import ( '@/lib/coingecko.actions' ) ;
1818
1919export default function CandlestickChart ( {
@@ -95,31 +95,50 @@ export default function CandlestickChart({
9595 useEffect ( ( ) => {
9696 if ( ! candleSeriesRef . current ) return ;
9797
98- // Convert timestamps from milliseconds to seconds while keeping full OHLC structure
99- const convertedToSeconds = ohlcData . map ( ( item ) => [
100- Math . floor ( item [ 0 ] / 1000 ) , // timestamp in seconds
101- item [ 1 ] , // open
102- item [ 2 ] , // high
103- item [ 3 ] , // low
104- item [ 4 ] , // close
105- ] as OHLCData ) ;
106- console . log ( '==== Updating convertedToSeconds:' , convertedToSeconds ) ;
107-
108- const merged = liveOhlcv
109- ? [ ...convertedToSeconds , liveOhlcv ]
110- : [ ...convertedToSeconds ] ;
111-
112- console . log ( '==== Updating merged:' , merged ) ;
113- // Sort ascending by time
98+ // Convert timestamps from milliseconds to seconds
99+ const convertedToSeconds = ohlcData . map (
100+ ( item ) =>
101+ [
102+ Math . floor ( item [ 0 ] / 1000 ) , // timestamp in seconds
103+ item [ 1 ] , // open
104+ item [ 2 ] , // high
105+ item [ 3 ] , // low
106+ item [ 4 ] , // close
107+ ] as OHLCData
108+ ) ;
109+
110+ let merged : OHLCData [ ] ;
111+
112+ if ( liveOhlcv ) {
113+ const liveTimestamp = liveOhlcv [ 0 ] ;
114+
115+ // Check if we need to update an existing candle or add a new one
116+ const lastHistoricalCandle =
117+ convertedToSeconds [ convertedToSeconds . length - 1 ] ;
118+
119+ if ( lastHistoricalCandle && lastHistoricalCandle [ 0 ] === liveTimestamp ) {
120+ // Update the last candle with live data
121+ merged = [ ...convertedToSeconds . slice ( 0 , - 1 ) , liveOhlcv ] ;
122+ } else {
123+ // Append new live candle
124+ merged = [ ...convertedToSeconds , liveOhlcv ] ;
125+ }
126+ } else {
127+ merged = convertedToSeconds ;
128+ }
129+
130+ // Sort ascending by time (in case of any ordering issues)
114131 merged . sort ( ( a , b ) => a [ 0 ] - b [ 0 ] ) ;
115132
116133 const converted = convertOHLCData ( merged ) ;
117134
118- console . log ( '==== Updating Candlestick Data:' , converted ) ;
119-
120135 candleSeriesRef . current . setData ( converted ) ;
121- chartRef . current ?. timeScale ( ) . fitContent ( ) ;
122- } , [ ohlcData , liveOhlcv , period ] ) ;
136+
137+ // Only fit content on initial load or period change, not on live updates
138+ if ( ! liveOhlcv || mode === 'historical' ) {
139+ chartRef . current ?. timeScale ( ) . fitContent ( ) ;
140+ }
141+ } , [ ohlcData , liveOhlcv , period , mode ] ) ;
123142
124143 return (
125144 < div className = 'candlestick-container' >
0 commit comments