I wrote the following code (minimally working example) that uses plotly
to show candlestick charts in real-time.
It works great.
However, the only issue I have is that every time I receive new data there will be a new plotly figure and over time I will end up having many opened figures, which I don’t want.
Is there any way to plot everything in a single plot and update the same figure with new data?
import pandas as pd
import plotly.graph_objects as go
from datetime import datetime
from time import sleep
import random
ohlc_data = pd.DataFrame(columns=["timestamp", "open", "high", "low", "close", "volume"])
fig = go.Figure(data=[go.Candlestick(x=[], open=[], high=[], low=[], close=[])])
fig.update_layout(title=f'Live Candlestick Chart', xaxis_title='Time', yaxis_title='Price')
def update_live_chart(fig, df):
fig.update_traces(x=df['timestamp'], open=df['open'], high=df['high'], low=df['low'], close=df['close'])
while True:
sleep(1)
new_data = pd.DataFrame([{
"timestamp": datetime.now().timestamp(),
"open": random.randint(100, 110),
"high": random.randint(100, 110),
"low": random.randint(100, 110),
"close": random.randint(100, 110),
"volume": random.randint(100, 110)
}])
ohlc_data = pd.concat([ohlc_data, new_data], ignore_index=True)
ohlc_data = ohlc_data.tail(100)
update_live_chart(fig, ohlc_data)
fig.show()
2