How to draw !? Real time candle stick chart in plotly

Hello friends

I have a question

I have a piece of code that I draw a candle stick diagram for myself

But I want it to be Real-time, something like Trading View

But I do not know how to do this in [plotly]

This is my code:

# collect the candlestick data from Binance
binance = ccxt.binanceusdm()
trading_pair = 'BTC/USDT'
candles = binance.fetch_ohlcv(trading_pair, '1m')
dates = []
open_data = []
high_data = []
low_data = []
close_data = []

# format the data to match the charting library
for candle in candles:
    dates.append(datetime.fromtimestamp(candle[0] / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f'))
    open_data.append(candle[1])
    high_data.append(candle[2])
    low_data.append(candle[3])
    close_data.append(candle[4])

# The latest status of the bar
Candleู€update = [dates[-1], open_data[-1], high_data[-1], low_data[-1], close_data[-1]]

fig = go.Figure(data=[go.Candlestick(x=dates,
                open=open_data, high=high_data,
                low=low_data, close=close_data)])

fig.show()

The part where the diagram is drawn is how the data should be updated without a new diagram being drawn (because I used the while loop and new diagrams were created), only a new candlestick is created!

1 Like

Hi, did you figure out a solution for your problem. i.e. to show live developing candlesticks in plotly?

@akarun: You should use dcc.Interval to make it live. Something as below:

import ccxt
from datetime import datetime
import plotly.graph_objects as go
import dash
import dash_bootstrap_components as dbc
from dash import Input, Output, State, dcc, html

# connect dahs page to main app
app = dash.Dash(__name__, title='Dashboard', external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div([
    dcc.Graph(id='candlestick', figure=fig),
    dcc.Interval(
            id='interval-component',
            interval=5*1000, # in milliseconds
            n_intervals=0
        )
])

@app.callback(Output('candlestick','figure'), Input('interval-component','n_intervals'))
def update_graph(n):

    binance = ccxt.binanceusdm()
    trading_pair = 'BTC/USDT'
    candles = binance.fetch_ohlcv(trading_pair, '1m')
    dates = []
    open_data = []
    high_data = []
    low_data = []
    close_data = []

    # format the data to match the charting library
    for candle in candles:
        dates.append(datetime.fromtimestamp(candle[0] / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f'))
        open_data.append(candle[1])
        high_data.append(candle[2])
        low_data.append(candle[3])
        close_data.append(candle[4])

    # The latest status of the bar
    Candleู€update = [dates[-1], open_data[-1], high_data[-1], low_data[-1], close_data[-1]]

    fig = go.Figure(data=[go.Candlestick(x=dates,
                open=open_data, high=high_data,
                low=low_data, close=close_data)])

    return fig
if __name__ == "__main__":
    app.run_server(debug=False)